Likou 654. The largest binary tree

topic:

Given an integer array nums with no repeated elements. A maximum binary tree constructed directly recursively from this array is defined as follows:

The root of the binary tree is the largest element in the array nums.
The left subtree is the largest binary tree recursively constructed from the left part of the maximum value in the array.
The right subtree is the largest binary tree recursively constructed from the right part of the maximum value in the array.

Example:

solution

The preorder that is generally used to construct a binary tree, because the root node is constructed first

Generally speaking: if the empty node (null pointer) is allowed to enter the recursion, no if is added. If the empty node is not allowed to enter the recursion, the if limit is added, and the termination condition will be adjusted accordingly.

Code

class Solution {
    
    
public:

    TreeNode* traversal(vector<int>& nums, int left, int right) {
    
    
        if (left >= right) return nullptr;

        //分割,找到局部最大值
        int delimitIndex = left;
        for (int i = left + 1; i < right; i++) {
    
    
            if (nums[i] > nums[delimitIndex]) {
    
    
                delimitIndex = i;
            } 
        }
        //创建节点,
        TreeNode* node = new TreeNode(nums[delimitIndex]);
        //左右节点返回值递归
        node->left = traversal(nums, left, delimitIndex);
        node->right = traversal(nums, delimitIndex + 1, right);

        return node;
    }
    TreeNode* constructMaximumBinaryTree(vector<int>& nums) {
    
    
        return traversal(nums, 0, nums.size());
    }
};

Guess you like

Origin blog.csdn.net/Matcha_/article/details/114063380