1,题目描述
给定一个不含重复元素的整数数组。一个以此数组构建的最大二叉树定义如下:
二叉树的根是数组中的最大元素。
左子树是通过数组中最大值左边部分构造出的最大二叉树。
右子树是通过数组中最大值右边部分构造出的最大二叉树。
通过给定的数组构建最大二叉树,并且输出这个树的根节点。
2,解题
思路:遍历数组把找到最大值
maxVal
,把根节点root
做出来,然后对maxVal
左边的数组和右边的数组进行递归调用,作为root
的左右子树TreeNode constructMaximumBinaryTree([3,2,1,6,0,5]) { // 找到数组中的最大值 TreeNode root = new TreeNode(6); // 递归调用构造左右子树 root.left = constructMaximumBinaryTree([3,2,1]); root.right = constructMaximumBinaryTree([0,5]); return root; }
class Solution {
public:
TreeNode* constructMaximumBinaryTree(vector<int>& nums) {
return buil(nums,0,nums.size()-1);
}
TreeNode* buil(vector<int>&nums,int lo,int hi)
{
if(lo>hi) return NULL;
int index;
auto max = max_element(nums.begin()+lo,nums.begin()+hi+1); // 范围是[) 左闭右开
index = max-nums.begin();
TreeNode* root = new TreeNode(*max);
root->left = buil(nums,lo,index-1);
root->right = buil(nums,index+1,hi);
return root;
}
};