LeetCode 654. Maximum Binary Tree最大二叉树 (C++)

题目:

Given an integer array with no duplicates. A maximum tree building on this array is defined as follow:

  1. The root is the maximum number in the array.
  2. The left subtree is the maximum tree constructed from left part subarray divided by the maximum number.
  3. The right subtree is the maximum tree constructed from right part subarray divided by the maximum number.

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:

  1. The size of the given array will be in the range [1,1000].

分析:

给定一个不含重复元素的整数数组。一个以此数组构建的最大二叉树定义如下:

  1. 二叉树的根是数组中的最大元素。
  2. 左子树是通过数组中最大值左边部分构造出的最大二叉树。
  3. 右子树是通过数组中最大值右边部分构造出的最大二叉树。

通过给定的数组构建最大二叉树,并且输出这个树的根节点。

每次选出数组中的最大值作为根节点,左子树就递归执行最大值的左侧,右子树递归执行最大值的右侧。当数组为空的时候返回空指针。

程序:

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

猜你喜欢

转载自www.cnblogs.com/silentteller/p/10909388.html