题解 | #牛群中的编号是否有效#

牛群中的编号是否有效

https://www.nowcoder.com/practice/2b4279d545124277a06a8e5eaa802375

一、知识点:

二叉树、中序遍历、栈

二、文字分析:

使用了中序遍历的迭代实现。我们使用一个栈来辅助遍历二叉树。将当前节点的左子树依次压入栈中,直到叶子节点。然后从栈中弹出节点,如果节点的值小于等于前一个节点的值,则不是有效的二叉搜索树,返回 false。否则,将当前节点设置为前一个节点,并处理当前节点的右子树。通过这种方式,我们能够按照递增顺序访问二叉树的节点。如果遍历完整个二叉树后没有发现非递增的节点值,那么该二叉树是有效的二叉搜索树,返回 true。

时间复杂度为O(N),空间复杂度为O(N)。

三、编程语言:

java

四、正确代码:

import java.util.*;

/*
 * public class TreeNode {
 *   int val = 0;
 *   TreeNode left = null;
 *   TreeNode right = null;
 *   public TreeNode(int val) {
 *     this.val = val;
 *   }
 * }
 */


public class Solution {
    public boolean isValidBST(TreeNode root) {
        if (root == null) {
            return true;
        }

        Stack<TreeNode> stack = new Stack<>();
        TreeNode current = root;
        TreeNode prev = null;

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

            current = stack.pop();

            if (prev != null && current.val <= prev.val) {
                return false;
            }

            prev = current;
            current = current.right;
        }

        return true;
    }
}

全部评论

相关推荐

点赞 收藏 评论
分享
牛客网
牛客企业服务