*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.

解法一:

第一种方法是中序遍历法。

因为如果是BST的话,中序遍历数一定是单调递增的,如果违反了这个规律,就返回false。

根据这一点我们只需要中序遍历这棵树,然后保存前驱结点,每次检测是否满足递增关系即可。注意以下代码我么用一个一个变量的数组去保存前驱结点,原因是java没有传引用的概念,如果传入一个变量,它是按值传递的,所以是一个备份的变量,改变它的值并不能影响它在函数外部的值,算是java中的一个小细节。代码如下:

 
 1 public boolean isValidBST(TreeNode root) {
 2     ArrayList<Integer> pre = new ArrayList<Integer>();
 3     pre.add(null);
 4     return helper(root, pre);
 5 }
 6 private boolean helper(TreeNode root, ArrayList<Integer> pre)
 7 {
 8     if(root == null)
 9         return true;
10     boolean left = helper(root.left,pre);
11     if(pre.get(0)!=null && root.val<=pre.get(0))
12         return false;
13     pre.set(0,root.val);
14     return left && helper(root.right,pre);
15 }

解法二:很牛。。

第二种方法是直接按照定义递归求解。 

“根据题目中的定义来实现,其实就是对于每个结点保存左右界,也就是保证结点满足它的左子树的每个结点比当前结点值小,右子树的每个结点比当前结 点值大。对于根节点不用定位界,所以是无穷小到无穷大,接下来当我们往左边走时,上界就变成当前结点的值,下界不变,而往右边走时,下界则变成当前结点 值,上界不变。如果在递归中遇到结点值超越了自己的上下界,则返回false,否则返回左右子树的结果。” 

/**
 * 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 helper(root, Long.MIN_VALUE, Long.MAX_VALUE);
    }

    boolean helper(TreeNode node, long min, long max) {
      if(node == null)
         return true;
     if(node.val > min 
         && node.val < max
         && helper(node.left,min,node.val)
         && helper(node.right,node.val,max))
         return true;
     else 
         return false;
    }
}

 上述两种方法本质上都是做一次树的遍历,所以时间复杂度是O(n),空间复杂度是O(logn)。

reference:http://stackoverflow.com/questions/499995/how-do-you-validate-a-binary-search-tree

http://www.cnblogs.com/springfor/p/3889729.html

http://blog.csdn.net/linhuanmars/article/details/23810735

原文地址:https://www.cnblogs.com/hygeia/p/4716930.html