Leetcode: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.

 

 

confused what "{1,#,2,3}" means? > read more on how binary tree is serialized on OJ.


OJ's Binary Tree Serialization:
The serialization of a binary tree follows a level order traversal, where '#' signifies a path terminator where no node exists below.

Here's an example:

   1
  / \
 2   3
    /
   4
    \
     5
The above binary tree is serialized as "{1,2,3,#,#,4,#,#,5}".

 

注意:二叉树表示采用 完全二叉树编号方法,如果相应编号的结点为空,则用#表示
 
分析:
根据BST定义,我们可以很快的写出类似代码: 对每个节点,如果每个节点都满足 左孩子节点值 < 当前节点值 < 右孩子节点值,则返回true
但是这个方法是错误的,且看 
   10
   /  \
  5   15     -------- binary tree (1)
     /  \
    6    20

 


我们可以看到:每个节点都满足:左孩子节点值 < 当前节点值 < 右孩子节点值
但是该二叉树很明显不是一颗BST

我们可以如下:
对于每一个子树,限制它的最大,最小值,如果超过则返回false。
对于根节点,最大最小都不限制;
每一层节点,左子树限制最大值小于根,右子树最小值大于根;

/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    bool isValidBST(TreeNode *root) {
        return isBST(root, INT_MIN, INT_MAX);
    }
    bool isBST(TreeNode* root, int low, int high) {
        if (root == NULL) return true;
        if (low < root->val && root->val < high
        && isBST(root->left, low, root->val) 
        && isBST(root->right, root->val, high) ) {
            return true;
        } else {
            return false;
        }
    }
};

 时间复杂度为O(n) n为节点总数

 空间复杂度为O(1) (忽略函数递归栈空间)

你可能感兴趣的:(Binary search)