larscheng / algo

0 stars 0 forks source link

【Check 51】2024-04-14 - 98. 验证二叉搜索树 #153

Open larscheng opened 2 months ago

larscheng commented 2 months ago

98. 验证二叉搜索树

larscheng commented 2 months ago

思路


```java

    //中序遍历升序数组
    //递归需要检查所有节点,迭代可以优化复杂度
    public boolean isValidBST(TreeNode root) {
        double lastNum = -Double.MAX_VALUE;
        Stack<TreeNode> stack = new Stack<>();

        while (root != null || !stack.isEmpty()) {
            while (root != null) {
                stack.push(root);
                root = root.left;
            }

            TreeNode node = stack.pop();
            if (node.val<=lastNum){
                return false;
            }
            lastNum = node.val;

            root = node.right;
        }
        return true;
    }

复杂度