代码随想录算法训练营第二十天| 654.最大二叉树, 617.合并二叉树 ,700.二叉搜索树中的搜索 ,98.验证二叉搜索树

LeetCode 654.最大二叉树

数组nums中至少有一个元素,采用区间左开右闭,每次找到最大值及下标,以最大值为分割点,再遍历左子树和右子树,代码如下:

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

LeetCode 617.合并二叉树 

两树遍历的关键点在于递归终止条件的确定:当root1为null时,合并的新节点应返回root2,同理如果root2为null,应返回root1,不考虑全为null的情况了,因为null加null还是null。代码如下:

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

LeetCode 700.二叉搜索树中的搜索

简单搜索题,递归终止条件:如果root为null则返回null;如果root值等于val,返回root;当层遍历处理:遍历左子树得到目标节点,如果不为空则返回该节点;否则继续遍历右子树,若不为null则返回该节点;上述均为null,则返回null。代码如下:

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

LeetCode 98.验证二叉搜索树

若为二叉搜索树,则中序遍历的结果应为升序,本题容易陷入两个陷阱:1.不能单纯的比较左节点小于中间节点,右节点大于中间节点就完事了;要比较的是 左子树所有节点小于中间节点,右子树所有节点大于中间节点。2.样例中最小节点可能是int的最小值,如果这样使用最小的int来比较也是不行的。所以都把maxVal改成了longlong最小值。如果测试数据中有 longlong的最小值,怎么办?不可能在初始化一个更小的值了吧。 建议避免初始化最小值,可以采取保存前一个节点的方法来进行是否升序的比较。代码如下:

class Solution {
    TreeNode pre = null;
    public boolean isValidBST(TreeNode root) {
        if(root == null) return true;
        boolean left = isValidBST(root.left);
        if(pre != null && pre.val >= root.val) return false;
        pre = root;
        boolean right = isValidBST(root.right);
        return left && right;
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值