leetcode-----98. 验证二叉搜索树

算法:中序遍历

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public boolean isValidBST(TreeNode root) {
        Stack<TreeNode> st = new Stack();
        long lastval = Long.MIN_VALUE;

        while (!st.empty() || root != null) {
            while (root != null) {
                st.push(root);
                root = root.left;
            }
            root = st.pop();
            if (root.val <= lastval) return false;
            lastval = (long)root.val;
            root = root.right;
        }
        return true;
    }
}

递归版本

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    long lastval = Long.MIN_VALUE;

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

        if (isValidBST(root.left)) {
            if (root.val > lastval) {
                lastval = root.val;
                return isValidBST(root.right);
            }
        }
        return false;
    }
}
上一篇:LeetCode 98. 验证二叉搜索树


下一篇:LeetCode 98. 验证二叉搜索树 | Python