Given an integer array with no duplicates. A maximum tree building on this array is defined as follow:
- The root is the maximum number in the array.
- The left subtree is the maximum tree constructed from left part subarray divided by the maximum number.
- The right subtree is the maximum tree constructed from right part subarray divided by the maximum number.
Construct the maximum tree by the given array and output the root node of this tree.
Example 1:
Input: [3,2,1,6,0,5]
Output: return the tree root node representing the following tree:
6
/ \
3 5
\ /
2 0
\
1
Note:The size of the given array will be in the range [1,1000].
算法分析:类似于二叉树的遍历,用递归来实现
C语言版
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
struct TreeNode* constructMaximumBinaryTree(int* nums, int numsSize) {
int i, index = 0, max = nums[0];
if(numsSize == 0)
return NULL;
for(i = 1; i < numsSize; i++)
{
if(max < nums[i])
{
index = i;
max = nums[i];
}
}
struct TreeNode* node = (struct TreeNode*)malloc(sizeof(struct TreeNode));
node->val = max;
node->left = constructMaximumBinaryTree(nums, index);
node->right = constructMaximumBinaryTree(nums + index + 1, numsSize - index - 1);
return node;
}
Python版
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def constructMaximumBinaryTree(self, nums):
"""
:type nums: List[int]
:rtype: TreeNode
"""
if nums:
index = nums.index(max(nums))
root = TreeNode(nums[index])
root.left = self.constructMaximumBinaryTree(nums[ : index])
root.right = self.constructMaximumBinaryTree(nums[index + 1: ])
return root
本文介绍了一种构建最大二叉树的方法,通过寻找数组中的最大值作为根节点,并递归构造左右子树。提供了C语言及Python两种实现方式。
3158

被折叠的 条评论
为什么被折叠?



