您的位置:首页 > 其它

leetcode--Validate Binary Search Tree

2015-06-11 18:41 567 查看
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.
分类:二叉树

题意:判断二叉树是否为排序二叉树

解法1:递归判断,递归时传入两个参数,一个是左界,一个是右界,节点的值必须在两个界的中间,同时在判断做子树和右子树时更新左右界

/**
* Definition for a binary tree node.
* public class TreeNode {
*     int val;
*     TreeNode left;
*     TreeNode right;
*     TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public boolean isValidBST(TreeNode root) {
return validate(root, null, null);
}

public boolean validate(TreeNode root, TreeNode min, TreeNode max) {
if(root==null) return true;
if(min!=null && root.val<=min.val) return false;
if(max!=null && root.val>=max.val) return false;
if(!validate(root.left, min, root)) return false;
if(!validate(root.right, root, max)) return false;
return true;
}
}


解法2:中序遍历,然后判断是否从小到大排序

/**
* Definition for a binary tree node.
* public class TreeNode {
*     int val;
*     TreeNode left;
*     TreeNode right;
*     TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public boolean isValidBST(TreeNode root) {
List<Integer> arr = new ArrayList<Integer>();
Inorder(root,arr);
for(int i=1;i<arr.size();i++){
if(arr.get(i-1)>=arr.get(i)) return false;
}
return true;
}

public void Inorder(TreeNode root,List<Integer> arr){
if(root!=null){
if(root.left!=null) Inorder(root.left,arr);
arr.add(root.val);
if(root.right!=null) Inorder(root.right,arr);
}
}
}


解法3:中序遍历,但是每次标记要访问节点的前一个节点,从而省去O(n)空间

public class Solution {
// Keep the previous value in inorder traversal.
TreeNode pre = null;

public boolean isValidBST(TreeNode root) {
// Traverse the tree in inorder.
if (root != null) {
// Inorder traversal: left first.
if (!isValidBST(root.left)) return false;

// Compare it with the previous value in inorder traversal.
if (pre != null && root.val <= pre.val) return false;

// Update the previous value.
pre = root;

// Inorder traversal: right last.
return isValidBST(root.right);
}
return true;
}
}

解法3的另外一种写法:

/**
* Definition for a binary tree node.
* public class TreeNode {
*     int val;
*     TreeNode left;
*     TreeNode right;
*     TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public boolean isValidBST(TreeNode root) {
if(Inorder(root)!=null) return false;
return true;
}

TreeNode pre = null;
public TreeNode Inorder(TreeNode root){
if(root==null) return null;
TreeNode left=Inorder(root.left);
if(left!=null) return left;
if(pre!=null&&pre.val>=root.val) return root;
pre = root;
TreeNode right=Inorder(root.right);
if(right!=null) return right;
return null;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: