首页 > 其他 > 详细

654. Maximum Binary Tree

时间:2020-09-26 19:01:34      阅读:75      评论:0      收藏:0      [点我收藏+]

问题:

用给定的数组,构成最大二叉树。

从数组中找到最大值,作为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函数

  • base:数组为空:end>=start
    • 返回 nullptr
  • 对于每个节点root :在nums[start, end]范围内
    • 找到最大值maxval,及其index:idx
      • root->val = maxval
      • root->left = 递归求解:nums[start, idx] 
      • root->right = 递归求解:nums[idx+1, end]

代码参考:

 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 };

 

654. Maximum Binary Tree

原文:https://www.cnblogs.com/habibah-chang/p/13734840.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!