Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

验证二叉搜索树 #9

Open
chaojun-zhang opened this issue Feb 2, 2020 · 0 comments
Open

验证二叉搜索树 #9

chaojun-zhang opened this issue Feb 2, 2020 · 0 comments

Comments

@chaojun-zhang
Copy link
Owner

递归遍历

class Solution {
    public boolean isValidBST(TreeNode root) {
        if (root==null) return true;
        return helper(root.left,Long.MIN_VALUE,root.val) && helper(root.right,root.val,Long.MAX_VALUE);
    }

    private boolean helper(TreeNode node ,long low,long high){
        if (node ==null) return true;
        if (node.val<=low || node.val>= high) return false;
        return helper(node.left,low,node.val) && helper(node.right,node.val,high);
        
    }
}

中序遍历法
当前遍历的元素必须大于上一个元素

class Solution {
  public boolean isValidBST(TreeNode root) {
    Stack<TreeNode> stack = new Stack();
    double inorder = - Double.MAX_VALUE;

    while (!stack.isEmpty() || root != null) {
      while (root != null) {
        stack.push(root);
        root = root.left;
      }
      root = stack.pop();
      // If next element in inorder traversal
      // is smaller than the previous one
      // that's not BST.
      if (root.val <= inorder) return false;
      inorder = root.val;
      root = root.right;
    }
    return true;
  }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant