2021.11.12 - SX07-20.最大二叉树

1. 题目

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

2. 思路

(1) 递归

  • 从给定的数组区间中找出最大值建立根结点,然后递归建立左右子树即可。

3. 代码

public class Test {
    
    
    public static void main(String[] args) {
    
    
    }
}

class TreeNode {
    
    
    int val;
    TreeNode left;
    TreeNode right;

    TreeNode() {
    
    
    }

    TreeNode(int val) {
    
    
        this.val = val;
    }

    TreeNode(int val, TreeNode left, TreeNode right) {
    
    
        this.val = val;
        this.left = left;
        this.right = right;
    }
}

class Solution {
    
    
    private int[] nums;

    public TreeNode constructMaximumBinaryTree(int[] nums) {
    
    
        this.nums = nums;
        return recur(0, nums.length - 1);
    }

    private TreeNode recur(int left, int right) {
    
    
        if (left > right) {
    
    
            return null;
        }
        int maxValue = Integer.MIN_VALUE;
        int maxIndex = left;
        for (int i = left; i <= right; i++) {
    
    
            if (nums[i] > maxValue) {
    
    
                maxValue = nums[i];
                maxIndex = i;
            }
        }
        TreeNode root = new TreeNode(maxValue);
        root.left = recur(left, maxIndex - 1);
        root.right = recur(maxIndex + 1, right);
        return root;
    }
}

猜你喜欢

转载自blog.csdn.net/qq_44021223/article/details/121286066