Maximum binary lt-654

Given an array of integers contain duplicate elements. Define a maximum binary tree in order to arrays constructed as follows:

Binary tree root is the largest element in the array.
Left subtree is constructed by the maximum value of the left part of the array the maximum binary tree.
Right subtree is constructed by the maximum value of the right part of the array the maximum binary tree.
Construction of the binary tree by the maximum given array, and outputs the root of this tree.

This question is a bit like having preorder and inorder traversal of a binary tree structure, values ​​and way to the construction of the left and right sub-tree root node, in order to construct a binary tree.

 public static TreeNode constructMaximumBinaryTree(int[] nums) {
        return recursion(nums, 0, nums.length - 1);
    }

    public static TreeNode recursion(int[] nums, int start, int end) {
        //结束递归条件
        if (start > end) {
            return null;
        }
        //这个判断也可以不要 
        if (start == end) {
            return new TreeNode(nums[start]);
        }
            int max = nums[start];
            int k = start;
            for (int i = start; i <= end; i++) {
                if (max <= nums[i]) {
                    k = i;
                    max = nums[i];
                }
            }
            TreeNode root = new TreeNode(max);
            root.left = recursion(nums, start, k - 1);
            root.right = recursion(nums, k + 1, end);
            return root;
    }

  

Guess you like

Origin www.cnblogs.com/shaomys/p/11819802.html