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

这篇博客主要探讨了四个关于二叉树的算法问题:如何构造最大二叉树,如何合并二叉树,如何在二叉搜索树中进行搜索,以及验证二叉树是否符合二叉搜索树的特性。博主通过思路解析、代码展示和注意事项,详细讲解了每个问题的关键点,强调了中序遍历在解决这些题目中的重要作用。
摘要由CSDN通过智能技术生成

654.最大二叉树

代码随想录

思路:

中序遍历,将最大值放在中间节点,在根据要求在不同区间内寻找其左右节点。

代码:

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

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

需要注意的点:

617.合并二叉树

代码随想录

思路:

代码:

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

需要注意的点:

700.二叉搜索树中的搜索

代码随想录

思路:

比较val和节点的值,决定向左搜索还是向右搜索

代码:

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

需要注意的点:

98.验证二叉搜索树

代码随想录

思路:

二叉搜索树中序遍历后值是从小到大排列,利用中序遍历不断更新最大值,遇到不符合条件的直接返回false。

代码:

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

需要注意的点:

1、设置max为全局变量

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值