leetcode98 Validate Binary Search Tree

题目:

Given a binary tree, determine if it is a valid binary search tree (BST).

Assume a BST is defined as follows:

  • The left subtree of a node contains only nodes with keys less than the node's key.
  • The right subtree of a node contains only nodes with keys greater than the node's key.
  • Both the left and right subtrees must also be binary search trees.

给出一棵二叉树,判断是否符合给定的规则

 

思路:

考虑二叉树的中序遍历。

二叉树的中序遍历是升序的,因此中序遍历后判断序列是否是升序即可。

 

代码:

复制代码
    public static boolean isValidBST(TreeNode root){
        if(root == null){
            return true;
        }
        Stack<TreeNode> ts = new Stack<TreeNode>();
        ArrayList<Integer> arr = new ArrayList<Integer>();
        TreeNode ptr = root;
        //中序遍历
        while(ptr != null || !ts.isEmpty()){
            while(ptr != null){
                ts.push(ptr);
                ptr = ptr.left;
            }

            if( !ts.isEmpty() ){
                ptr = ts.pop();
                arr.add(ptr.val);
                ptr = ptr.right;
            }
        }
        int index = 0;
        int[] arrs = new int[arr.size()];
        for(int i: arr){
            arrs[index++] = i;
        }
        //判断中序遍历得到的序列是否是升序的
        index = arrs[0];
        boolean flag = true;
        for(int i = 1; i < arr.size(); i++){
            if(index >= arrs[i]){
                flag = false;
                break;
            }
            index = arrs[i];
        }
        return flag;
    }
复制代码

代码优化:

上述方法中,首先是将中序序列存储在集合中,为了判断升序方便又转换为数组,比较繁琐。

其实无需存储中序序列,在中序遍历过程中进行判断即可,一旦不符合升序条件就返回false。

 

代码:

复制代码
    //代码优化(中序遍历过程中判断即可)
    public static boolean isValidBST(TreeNode root){
        if(root == null){
            return true;
        }
        Stack<TreeNode> ts = new Stack<TreeNode>();
        TreeNode ptr = root;
        TreeNode pre = null;
        //中序遍历
        while(ptr != null || !ts.isEmpty()){
            while(ptr != null){
                ts.push(ptr);
                ptr = ptr.left;
            }

            if( !ts.isEmpty() ){
                ptr = ts.pop();
                if( pre != null && pre.val >= ptr.val){
                    return false;
                }
                pre = ptr;
                ptr = ptr.right;
            }
        }
        return true;
        
    }
复制代码

 

posted @   沧浪少年  阅读(186)  评论(0编辑  收藏  举报
编辑推荐:
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
阅读排行:
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 【杭电多校比赛记录】2025“钉耙编程”中国大学生算法设计春季联赛(1)
点击右上角即可分享
微信分享提示