您的位置:首页 > 其它

LeetCode-98. Validate Binary Search Tree

2017-12-22 08:52 537 查看
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.

题目要求

判断给定的一棵树是否为有效的二叉搜索树

方法一

利用中序遍历的结果来判断

二叉搜索树的中序遍历结果是一个递增数列,所以我们可以将其中序遍历得到的val值保存成集合数组,再判断这个集合数组是否是递增数组。

/**
* 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) {
List<Integer> treeList=new ArrayList<Integer>();
inOrderTraversal(root,treeList);
for(int i=1;i<treeList.size();++i)
{
if(treeList.get(i-1)>=treeList.get(i))
return false;
}
return true;
}
public void inOrderTraversal(TreeNode root,List<Integer> treeList)
{
if(root==null)
return;
inOrderTraversal(root.left,treeList);
treeList.add(root.val);
inOrderTraversal(root.right,treeList);
}
}


方法二

非递归解法

此过程和http://blog.csdn.net/polar_geass/article/details/78859952中的非递归解法很像,不同之处在于步骤三,在步骤三中我们需要将当前弹出的节点和上次弹出的节点值进行判断,如果当前值小说明不是有效的二叉搜索树,直接返回false。

class Solution {
public boolean isValidBST(TreeNode root) {
if(root==null)
return true;
Stack<TreeNode> s=new Stack<>();
TreeNode pre=null;
while(root!=null||!s.isEmpty())
{
while(root!=null)
{
s.push(root);
root=root.left;
}
root=s.pop();
if(pre!=null&&root.val<=pre.val)
return false;
pre=root;
root=root.right;
}
return true;
}
}


方法三

递归解法

在递归过程中,使用两个变量保存当前的最大值和最小值,这算是一个比较投机取巧的方法。

class Solution {
public boolean isValidBST(TreeNode root) {
return isValidBST(root, Long.MIN_VALUE, Long.MAX_VALUE);
}
public boolean isValidBST(TreeNode root, long minVal, long maxVal) {
if (root == null) return true;
if (root.val >= maxVal || root.val <= minVal) return false;
return isValidBST(root.left, minVal, root.val) && isValidBST(root.right, root.val, maxVal);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  二叉树 LeetCode