Leetcode 刷题 二叉树

654. 最大二叉树

和之前的通过后序遍历 中序遍历构造二叉树几乎差不多

通过数组 和 下标begin end 来 划分左子树 和 右子树

class Solution {

    public TreeNode constructMaximumBinaryTree(int[] nums) {
        return buildTree(nums, 0, nums.length);
    }

    private TreeNode buildTree(int[] nums, int begin, int end){
        if(begin >= end){
            return null;
        }
        int max = -1;
        int index = -1;
        for(int i = begin; i < end; i++){
            if(nums[i] > max){
                max = nums[i];
                index = i;
            }
        }
        TreeNode root = new TreeNode(max);
        root.left = buildTree(nums, begin, index);
        root.right = buildTree(nums, index + 1, end);
        return root;
    }
}

 617. 合并二叉树

使用什么顺序遍历都是可以的

class Solution {
    public TreeNode mergeTrees(TreeNode root1, TreeNode root2) {
        if(root1 == null && root2 == null){
            return null;
        }
        if(root1 != null && root2 == null){
            return root1;
        }
        if(root1 == null && root2 != null){
            return root2;
        }
        TreeNode root = new TreeNode(root1.val + root2.val);  // 中

        root.left = mergeTrees(root1.left, root2.left);   // 左
        root.right = mergeTrees(root1.right, root2.right);  // 右

        return root;
    }
}

 

700. 二叉搜索树中的搜索 

注意是二叉搜索树

可以使用二叉搜索树的特性

递归函数需要有返回值来提前终止递归   因为找到了就可以直接返回了 没必要在搜索下去

 

普通的二叉树的解法  注意 通过判断left的值来判断是否需要提前返回

class Solution {
    // 递归,普通二叉树
    public TreeNode searchBST(TreeNode root, int val) {
        if (root == null || root.val == val) {
            return root;
        }
        TreeNode left = searchBST(root.left, val);
        if (left != null) {
            return left;
        }
        return searchBST(root.right, val);
    }
}

 使用二叉搜索树的特征解法

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

98. 验证二叉搜索树

   和上一题一样 通过递归的返回值来提前判断


class Solution {
    TreeNode max = null;
    public boolean isValidBST(TreeNode root) {
        if(root == null){
            return true;
        }
        
        // 左
        boolean left = isValidBST(root.left);
        if(!left){
            return false;
        }

        // 中
        if(max != null && root.val <= max.val){
            return false;
        }
        max = root;

        //右
        boolean right = isValidBST(root.right);

        return right;
    }
}

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值