您的位置:首页 > 其它

【判断二叉搜索树】Validate Binary Search Tree

2014-03-12 23:06 447 查看
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);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐