问题:
用给定的数组,构成最大二叉树。
从数组中找到最大值,作为root,其index以左,作为左子树。index以右,作为右子树。
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: The size of the given array will be in the range [1,1000].
解法:Binary Tree(二叉树)
递归:help函数
代码参考:
1 /** 2 * Definition for a binary tree node. 3 * struct TreeNode { 4 * int val; 5 * TreeNode *left; 6 * TreeNode *right; 7 * TreeNode() : val(0), left(nullptr), right(nullptr) {} 8 * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} 9 * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} 10 * }; 11 */ 12 class Solution { 13 public: 14 TreeNode* help(vector<int>& nums, int start, int end) { 15 if(end<=start) return nullptr; 16 int maxval = INT_MIN; 17 int idx = 0; 18 for(int i=start; i<end; i++) { 19 if(nums[i]>maxval) { 20 maxval = nums[i]; 21 idx = i; 22 } 23 } 24 TreeNode* root = new TreeNode(maxval); 25 //child: 26 root->left = help(nums, start, idx); 27 root->right = help(nums, idx+1, end); 28 return root; 29 } 30 TreeNode* constructMaximumBinaryTree(vector<int>& nums) { 31 return help(nums, 0, nums.size()); 32 } 33 };
原文:https://www.cnblogs.com/habibah-chang/p/13734840.html