自学内容网 自学内容网

力扣654,最大二叉树

654. 最大二叉树 - 力扣(LeetCode)

解法一:每次构建左右两边的树都新建一个新数组,比较耗空间

/**
 * 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) {
        TreeNode root = new TreeNode();
        if(nums.length==1){
            root.val = nums[0];
            return root;
        }
        int maxValue = nums[0];
        int index = 0;
        for(int i =0;i<nums.length;i++){
            if(nums[i]>maxValue){
                maxValue = nums[i];
                index = i;
            }
        }
        root.val = maxValue;
        if(index>0){//左边
            int[] nums_l = Arrays.copyOfRange(nums,0,index);
            root.left = constructMaximumBinaryTree(nums_l);
        }
        if(index<nums.length-1){//右边
            int[] nums_r = Arrays.copyOfRange(nums,index+1,nums.length);
            root.right = constructMaximumBinaryTree(nums_r);
        }
        return 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 find(int[] nums,int begin,int end){
        TreeNode root = new TreeNode();
        if(begin==end){
            root.val = nums[begin];
            return root;
        }
        int maxValue =Integer.MIN_VALUE;
        int index = -1;
        for(int i =begin;i<=end;i++){
            if(nums[i]>maxValue){
                maxValue = nums[i];
                index = i;
            }
        }
        root.val = maxValue;
        if(index>begin){
            root.left = find(nums,begin,index-1);
        }
        if(index<end){
            root.right = find(nums,index+1,end);
        }
        return root;
    }
    public TreeNode constructMaximumBinaryTree(int[] nums) {
        return find(nums,0,nums.length-1);
    }
}

 


原文地址:https://blog.csdn.net/qq_62319385/article/details/138203308

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!