[leetcode]654. Maximum Binary Tree

[leetcode]654. Maximum Binary Tree


Analysis

周二快乐~—— [ummm~]

Given an integer array with no duplicates. A maximum tree building on this array is defined as follow:
The root is the maximum number in the array.
The left subtree is the maximum tree constructed from left part subarray divided by the maximum number.
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.
递归建树,类似于快排~

Implement

/**
 * 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.empty())
            return NULL;
        int max_nums = INT_MIN;
        int max_index = 0;
        for(int i=0; i<nums.size(); i++){
            if(max_nums < nums[i]){
                max_nums = nums[i];
                max_index = i;
            }
        }
        TreeNode* node = new TreeNode(max_nums);
        vector<int> left = vector<int>(nums.begin(), nums.begin()+max_index);
        vector<int> right = vector<int>(nums.begin()+max_index+1, nums.end());
        node->left = constructMaximumBinaryTree(left);
        node->right = constructMaximumBinaryTree(right);
        return node;
    }
};

猜你喜欢

转载自blog.csdn.net/weixin_32135877/article/details/81320682
今日推荐