Given an integer array with no duplicates. A maximum tree building on this array is defined as follow:
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:
给定一个不含重复元素的整数数组。一个以此数组构建的最大二叉树定义如下:
通过给定的数组构建最大二叉树,并且输出这个树的根节点。
每次选出数组中的最大值作为根节点,左子树就递归执行最大值的左侧,右子树递归执行最大值的右侧。当数组为空的时候返回空指针。
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: TreeNode* constructMaximumBinaryTree(vector<int>& nums) { if(nums.size() == 0) return nullptr; auto it = max_element(nums.begin(), nums.end()); TreeNode* root = new TreeNode(*it); vector<int> l(nums.begin(), it); vector<int> r(it+1, nums.end()); root->left = constructMaximumBinaryTree(l); root->right = constructMaximumBinaryTree(r); return root; } };
LeetCode 654. Maximum Binary Tree最大二叉树 (C++)
原文:https://www.cnblogs.com/silentteller/p/10909388.html