Day20 二叉树 part06

Day20 二叉树 part06

654.最大二叉树

我的思路:
类似从中序后序遍历的数组重建二叉树,只用对一个数组进行划分处理

解答:

class Solution {
    public TreeNode constructMaximumBinaryTree(int[] nums) {
        if(nums == null || nums.length == 0) {
            return null;
        }
        return constructMBT(nums, 0, nums.length - 1);
    }
    public TreeNode constructMBT(int[] nums, int start, int end) {
        if(start > end) {
            return null;
        }
        int rootindex = findMaxValue(nums, start, end);
        TreeNode root = new TreeNode(nums[rootindex]);
        root.left = constructMBT(nums, start, rootindex - 1);
        root.right = constructMBT(nums, rootindex + 1, end);
        return root;
    }
    public int findMaxValue(int[] nums, int start, int end) {
        int maxIndex = start;
        for(int i = start; i <= end; i ++ ) {
            if(nums[i] > nums[maxIndex]) {
                maxIndex = i;
            }
        }
        return maxIndex;
    }
}

617.合并二叉树

我的思路:
合并根节点,合并左子树和合并右子树,递归代码写出来很简单,但是如何递归还是要debug清楚

解答:

class Solution {
    public TreeNode mergeTrees(TreeNode root1, TreeNode root2) {
        if(root1 == null) {
            return root2;
        }
        if(root2 == null) {
            return root1;
        }
        TreeNode merge = new TreeNode(root1.val + root2.val);
        merge.left = mergeTrees(root1.left, root2.left);
        merge.right = mergeTrees(root1.right, root2.right);
        return merge;

    }
}

700.二叉搜索树中的搜索

我的思路:
需要定义一个新结点(结点值和root相同),进行递归搜索,并且不断更新

解答:

class Solution {
    public TreeNode searchBST(TreeNode root, int val) {
        if(root == null) {
            return null;
        }
        if(root.val == val) {
            return root;
        }
        TreeNode res = new TreeNode(root.val);
        if(root.val > val) {
            res = searchBST(root.left, val);
        }
        if(root.val < val) {
            res = searchBST(root.right, val);
        }
        return res;
    }
}

98.验证二叉搜索树

我的思路:
用min和max限制范围,找到叶子结点(root == null)返回true

解答:

class Solution {
    public boolean isValidBST(TreeNode root) {
        return BTS(root, null, null);
    }
    public boolean BTS(TreeNode root, Integer min, Integer max) {
        if(root == null) {
            return true;
        }
        if((min != null && root.val <= min) || (max != null && root.val >= max)) {
            return false;
        }
        return BTS(root.left, min, root.val) && BTS(root.right, root.val, max);
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值