654. Maximum Binary Tree

网友投稿 245 2022-12-01

654. Maximum Binary Tree

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.

Example 1: Input: [3,2,1,6,0,5] Output: return the tree root node representing the following tree:

\ 3 5 \ / 2 0 \

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

/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */class Solution { public TreeNode constructMaximumBinaryTree(int[] nums) { return construct(nums, 0, nums.length); } public TreeNode construct(int[] nums, int l, int r) { if (l == r) return null; int max_i = max(nums, l, r); TreeNode root = new TreeNode(nums[max_i]); root.left = construct(nums, l, max_i); root.right = construct(nums, max_i + 1, r); return root; } public int max(int[] nums, int l, int r) { int max_i = l; for (int i = l; i < r; i++) { if (nums[max_i] < nums[i]) max_i = i; } return

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:springboot动态调整日志级别的操作大全
下一篇:Java实现红黑树(平衡二叉树)的详细过程
相关文章

 发表评论

暂时没有评论,来抢沙发吧~