/**
 * public class TreeNode {
 *   public int key;
 *   public TreeNode left;
 *   public TreeNode right;
 *   public TreeNode(int key) {
 *     this.key = key;
 *   }
 * }
 */
public class Solution {
  public boolean isBST(TreeNode root) {
    // Write your solution here.
    return bstHelper(root, Integer.MIN_VALUE, Integer.MAX_VALUE);
  }

  private boolean bstHelper(TreeNode root, int min, int max) {
    if (root == null) {
      return true;
    }
    if (root.key <= min || root.key >= max) {
      return false;
    }

    return bstHelper(root.left, min, root.key) && bstHelper(root.right, root.key, max); 
  }
}

左子树的最大值要小于跟节点的值, 右子树的最小值要大于跟节点的值。

worst case:是bst,everynode 走一遍, 每个nodeO(1),总的O(n)

results matching ""

    No results matching ""