java二叉树 最大值_leetcode刷题笔记-654. 最大二叉树(java实现)
題目描述
給定一個不含重復(fù)元素的整數(shù)數(shù)組 nums 。一個以此數(shù)組直接遞歸構(gòu)建的 最大二叉樹 定義如下:
二叉樹的根是數(shù)組 nums 中的最大元素。
左子樹是通過數(shù)組中 最大值左邊部分 遞歸構(gòu)造出的最大二叉樹。
右子樹是通過數(shù)組中 最大值右邊部分 遞歸構(gòu)造出的最大二叉樹。
返回有給定數(shù)組 nums 構(gòu)建的 最大二叉樹 。
示例 1:
輸入:nums = [3,2,1,6,0,5]
輸出:[6,3,5,null,2,0,null,null,1]
解釋:遞歸調(diào)用如下所示:
- [3,2,1,6,0,5] 中的最大值是 6 ,左邊部分是 [3,2,1] ,右邊部分是 [0,5] 。
- [3,2,1] 中的最大值是 3 ,左邊部分是 [] ,右邊部分是 [2,1] 。
- 空數(shù)組,無子節(jié)點。
- [2,1] 中的最大值是 2 ,左邊部分是 [] ,右邊部分是 [1] 。
- 空數(shù)組,無子節(jié)點。
- 只有一個元素,所以子節(jié)點是一個值為 1 的節(jié)點。
- [0,5] 中的最大值是 5 ,左邊部分是 [0] ,右邊部分是 [] 。
- 只有一個元素,所以子節(jié)點是一個值為 0 的節(jié)點。
- 空數(shù)組,無子節(jié)點。
示例 2:
輸入:nums = [3,2,1]
輸出:[3,null,2,null,1]
提示:
1 <= nums.length <= 1000
0 <= nums[i] <= 1000
nums 中的所有整數(shù) 互不相同
解題思路
構(gòu)造二叉樹的問題,根節(jié)點要做的就是把想辦法把自己構(gòu)造出來。要遍歷數(shù)組把找到最大值 maxVal,把根節(jié)點 root 做出來,然后對 maxVal 左邊的數(shù)組和右邊的數(shù)組進行遞歸調(diào)用,作為 root 的左右子樹。對于每個根節(jié)點,只需要找到當前 nums 中的最大值和對應(yīng)的索引,然后遞歸調(diào)用左右數(shù)組構(gòu)造左右子樹即可。
解題代碼
/**
* Definition for a binary tree node.
* public 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 {
public TreeNode constructMaximumBinaryTree(int[] nums) {
return build(nums, 0, nums.length);
}
public TreeNode build(int[] nums, int low, int high) {
//結(jié)束條件
if(low >= high) {
return null;
}
int index = -1, maxVal = Integer.MIN_VALUE;
//查找數(shù)組給定范圍內(nèi)的最大值
for(int i=low; i
if(maxVal < nums[i]) {
maxVal = nums[i];
index = i;
}
}
//最大值作為跟節(jié)點
TreeNode root = new TreeNode(maxVal);
//遞歸左子樹
root.left = build(nums, low, index);
//遞歸右子樹
root.right = build(nums, index+1, high);
return root;
}
}
總結(jié)
以上是生活随笔為你收集整理的java二叉树 最大值_leetcode刷题笔记-654. 最大二叉树(java实现)的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: java jtable应用源码_JTab
- 下一篇: 字节码是java虚拟机的指令组_JVM?