zoukankan      html  css  js  c++  java
  • LeetCode98. 验证二叉搜索树

    ☆☆思路:中序遍历时,判断当前节点是否大于中序遍历的前一个节点,如果大于,满足BST,继续遍历;否则返回false。

        技巧点:保存前一个节点 + 中序遍历

    class Solution {
        TreeNode pre = null;
        public boolean isValidBST(TreeNode root) {
            if (root == null) return true;
            // 访问左子树
            if (!isValidBST(root.left)) {
                return false;  // 剪枝
            }
            // 访问当前节点
            if (pre != null && pre.val >= root.val) {
                return false;
            }
            pre = root;
            // 访问右子树
            return isValidBST(root.right);
            /**
             * 中序遍历(非递归)
             */
            /*
            if (root == null) return true;
            Stack<TreeNode> stack = new Stack<>();
            TreeNode pre = null;
            while (!stack.isEmpty() || root != null) {
                while (root != null) {
                    stack.push(root);
                    root = root.left;
                }
                root = stack.pop();
                if (pre != null && pre.val >= root.val) {
                    return false;
                }
                pre = root;
                root = root.right;
            }
            return true;
            */
        }
    }
  • 相关阅读:
    [原]Linux 命令行浏览器
    Linux 命令行浏览器
    [原]Linux 命令行 发送邮件
    Linux 命令行 发送邮件
    [原]Linux 修改时区
    Linux 修改时区
    [原]Ubuntu 下安装Mongodb
    离线解密RDP凭证密码
    [Win]权限维持
    Nginx反向代理
  • 原文地址:https://www.cnblogs.com/HuangYJ/p/14189487.html
Copyright © 2011-2022 走看看