代码随想录day20| 654.最大二叉树、617. 合并二叉树、700.二叉搜索树中的搜索、98.验证二叉搜索树

本文介绍了LeetCode中的三个与二叉树相关的问题:如何构建最大二叉树,合并两个二叉树,以及在二叉搜索树中查找和验证节点。通过递归方法展示了解决这些问题的关键思路。
摘要由CSDN通过智能技术生成

leetcode 654.最大二叉树

注意:×

  1. 使用外面的build函数而不是直接使用原本的constructMaximumBinaryTree函数
  2. 注意lo和hi的使用,在for循环中是[lo,hi]
    public TreeNode constructMaximumBinaryTree(int[] nums) {
        return build(nums,0,nums.length-1);
    }

    private TreeNode build(int[] nums, int lo, int hi) {
        if (lo>hi){return null;}

        int index = -1;
        int maxValue = Integer.MIN_VALUE;
        for (int i = lo; i <= hi; i++) {
            int tmp = nums[i];
            if (tmp>maxValue){
                index = i;
                maxValue = tmp;
            }
        }

        TreeNode root = new TreeNode(maxValue);
        root.left = build(nums,lo,index-1);
        root.right = build(nums,index+1,hi);

        return root;
    }

leetcode617. 合并二叉树

注意:√

  1. 学习了上一题的内容,其实还是好写的
    public TreeNode mergeTrees(TreeNode root1, TreeNode root2) {
        return merge(root1, root2);
    }

    private TreeNode merge(TreeNode root1, TreeNode root2) {
        if (root1 == null) {
            return root2;
        } else if(root2 == null) {
            return root1;
        }
        
        // 合并操作
        int rootVal = root1.val+ root2.val;
        TreeNode root = new TreeNode(rootVal);
        root.left = merge(root1.left,root2.left);
        root.right = merge(root1.right,root2.right);
        
        // 返回值
        return root;
    }

leetcode700.二叉搜索树中的搜索

注意:√

  1. 看完书,一遍过
  2. 注意第一段的写法,需要学习深刻理解递归
    public TreeNode searchBST(TreeNode root, int val) {
        if (root == null){return null;}
        if (root.val>val){
            return searchBST(root.left, val);
        }else if (root.val<val){
            return searchBST(root.right, val);
        }
		return root;
    }



    public TreeNode searchBST(TreeNode root, int val) {
        if (root == null){return null;}
        TreeNode node = null;
        if (root.val>val){
            node = searchBST(root.left, val);
        }else if (root.val<val){
            node = searchBST(root.right, val);
        }else if(root.val == val){
            return root;
        }

        return node;
    }

leetcode98.验证二叉搜索树

注意:×

  1. 看书后抄的,记得回头看
    public boolean isValidBST(TreeNode root) {
        return isValid(root,null,null);
    }

    private boolean isValid(TreeNode root, TreeNode min, TreeNode max) {
        if (root == null){return true;}
        
        if (min!=null && root.val <= min.val){return false;}
        if (max!=null && root.val >= max.val){return false;}
        
        return isValid(root.left,min,root) && isValid(root.right, root, max);
    }
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值