原题:
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; } 每次扫描下数组,依次递归就好。