Given a binary tree, determine if it is a valid binary search tree (BST).
Assume a BST is defined as follows:
- The left subtree of a node contains only nodes with keys less than the node's key.
- The right subtree of a node contains only nodes with keys greater than the node's key.
- Both the left and right subtrees must also be binary search trees.
递归解法:使用中序遍历,通过设定的pre节点值和当前遍历值相比较,若符合二叉搜索树的定义则返回真
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
private TreeNode pre=null;
public boolean inorder(TreeNode root){
if(root == null) return true;
boolean left = inorder(root.left);
if(pre != null && pre.val>=root.val)
return false;
pre = root;
boolean right = inorder(root.right);
return left && right;
}
public boolean isValidBST(TreeNode root) {
return inorder(root);
}
}
解法二:非递归实现中序遍历,并进行pre和当前遍历值的判断
public class Solution {
public boolean inorder(TreeNode root){
if(root == null) return true;
Stack<TreeNode> s = new Stack<TreeNode>();
TreeNode p = root;
while(p!=null || !s.isEmpty()){
while(p!=null){
s.push(p);
p = p.left;
}
if(!s.isEmpty()){
TreeNode t = s.pop();
if(pre!=null && pre.val>=t.val) return false;
pre = t;
p = t.right;
}
}
return true;
}
public boolean isValidBST(TreeNode root) {
return inorder(root);
}
}