代码
1 class Solution {
2 public:
3 TreeNode* constructMaximumBinaryTree(vector<int>& nums) {
4 //数组长度是一直接返回
5 if(nums.size() == 1) {TreeNode *root = new TreeNode(nums[0]); return root;}
6 //找到最大元素的位置
7 int Index = 0;
8 for(int i = 1;i < nums.size();i++){
9 if(nums[Index] < nums[i]) Index = i;
10 }
11 //建立根节点
12 TreeNode *root = new TreeNode(nums[Index]);
13
14 //分割左右树,左闭右开
15 vector<int>left(nums.begin(),nums.begin()+Index);
16 vector<int>right(nums.begin()+Index+1,nums.end());
17
18 //递归处理左右子树
19 if(left.size()) root->left = constructMaximumBinaryTree(left);
20 if(right.size()) root->right = constructMaximumBinaryTree(right);
21
22 return root;
23 }
24 };
参考
LeetCode105. 从前序与中序遍历序列构造二叉树