您的位置:首页 > 其它

leetcode 654. Maximum Binary Tree

2017-08-07 09:24 393 查看
原题:

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

代码如下:
struct TreeNode* constructMaximumBinaryTree(int* nums, int numsSize) {
if(numsSize==0)
return nums;
int max=INT_MIN;
int flag=-1;
for(int n=0;n<numsSize;n++)
{
if(*(nums+n)>max)
{
max=*(nums+n);
flag=n;
}
}
struct TreeNode* root;
root=(struct TreeNode*)malloc(sizeof(struct TreeNode));
root->val=max;
if(flag!=0)
root->left=constructMaximumBinaryTree(nums, flag);
else
root->left=NULL;
if(flag!=numsSize-1)
root->right=constructMaximumBinaryTree(nums+flag+1, numsSize-flag-1);
else
root->right=NULL;
return root;
}

每次扫描下数组,依次递归就好。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: