您的位置:首页 > 其它

98 Validate Binary Search Tree

2015-12-01 21:48 330 查看
题目链接:https://leetcode.com/problems/validate-binary-search-tree/

题目:

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. 对给定二叉树进行中序遍历

2. 每遍历一个结点,就把该结点的值与上次被遍历的结点的值进行比较,即 pre.val < root.val

3. 若上一个被遍历结点的值大于等于当前结点的值,说明其中序遍历不是一个单调递增序列,故该二叉树不是一棵二叉搜索树

4. 否则,继续中序遍历。直至所有结点遍历完成

存储结构上,利用数组存储中序遍历的结点值,以方便结点值的比较。

自己的想法是利用 ArrayList 始终只存储一个结点的值。即,比较完成后删除上次遍历的值,再加入当前结点的值。

大神的思路和我的一致,也是利用中序遍历的特点。他利用 ArrayList 存储了所有遍历过的结点值,每次遍历到的新值都插入到 list 的第 0 个位置上,这样在比较的时候始终与链表第 0 个元素进行比较。

参考链接:/article/1378251.html

自己的代码实现:

/**
* 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(root == null)
return true;
return helper(root, new ArrayList<Integer>());
}
boolean helper(TreeNode root, List<Integer> k) {
boolean left = false;
boolean right = false;
if(root.left != null) {
left = helper(root.left, k);
if(!left)
return false;
}
if(!k.isEmpty()) {
if(root.val <= k.get(0))
return false;
else
k.remove(0);
}
k.add(root.val);
if(root.right != null) {
right = helper(root.right, k);
if(!right)
return false;
}
return true;
}
}


74 / 74 test cases passed.
Status: Accepted
Runtime: 2 ms


大神的代码实现:

/**
* 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(root == null)
return true;
List<Integer> pre = new ArrayList<Integer>();
pre.add(null);
return helper(root, pre);
}
boolean helper(TreeNode root, List<Integer> pre) {
if(root == null)
return true;
boolean left = helper(root.left, pre);
if(pre.get(0) != null && root.val <= pre.get(0))
return false;
pre.set(0, root.val);
return left && helper(root.right, pre);
}
}


74 / 74 test cases passed.
Status: Accepted
Runtime: 2 ms


大神还提出了第二种方法:

第二种方法是根据题目中的定义来实现。

- 其实就是对于每个结点保存左右界,也就是保证结点满足它的左子树的每个结点比当前结点值小,右子树的每个结点比当前结点值大。

- 对于根节点不用定位界,所以是无穷小到无穷大,接下来当我们往左边走时,上界就变成当前结点的值,下界不变,而往右边走时,下界则变成当前结点值,上界不变。

- 如果在递归中遇到结点值超越了自己的上下界,则返回false,否则返回左右子树的结果。

代码如下:

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