LeetCode 654 最大二叉树
作者:互联网
问题描述:
解题思路:
遍历数组找出最大的数作为root节点。把数组以最大值为分界线,将数组分为两个子数组。以同样的思路递归左右两个子数组,构建出最大二叉树。
题解:
/**
* 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 construct(nums,0,nums.length-1);
}
TreeNode construct(int[]nums,int lo,int hi){
if (lo > hi) {
return null;
}
int maxValue = Integer.MIN_VALUE ;
int index = -1;
for(int i = lo;i<=hi;i++){
if(nums[i]>maxValue){
maxValue = nums[i];
index = i;
}
}
TreeNode node = new TreeNode(maxValue);
node.left = construct(nums,lo,index-1);
node.right = construct(nums,index+1,hi);return node;
}
}
标签:node,right,TreeNode,val,nums,int,654,二叉树,LeetCode 来源: https://blog.csdn.net/qq_23604953/article/details/122157812