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.

Example 1:

    2
   / \
  1   3

Binary tree[2,1,3], return true.

Example 2:

    1
   / \
  2   3

Binary tree[1,2,3], return false.

思路分析

这道题我在第一次做的时候跳进了一个坑,我当时的思路是用递归的实现,怎么实现呢?就是比较node的左子树的key是不是小于node的key,并且比较node的右子树的key是不是大于node的key。这样做又一个什么问题呢?根据BST的概念,树的任何节点的左子树上的所有节点的key都要小于这个节点的key,同时右子树上的所有节点的key都要大于这个节点的key,那么问题就是,不能仅仅比较node的key与node的左子树/右子树的key。

下面的就是错误的实现:

class Solution {
    public boolean isValidBST(TreeNode root) {
        if (root == null) return true;
        boolean leftCheck = true;
        boolean rightCheck = true;
        if (root.left != null) leftCheck = root.left.val < root.val;
        if (root.right != null) rightCheck = root.right.val > root.val;
        return isValidBST(root.left) && isValidBST(root.right) && leftCheck && rightCheck;
    }
}

那么这道题如何来实现呢?一个点就是考虑BST的特点,如果对一个BST进行inorder traverse,就会得到一个ascending的有序数组。能不能一边对BST进行inorder traverse,一边比较相邻的值是不是升序呢?沿着这个思路就可以用stack+iterative的方式来实现

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

results matching ""

    No results matching ""