原题
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:
Input:
2
/ \
1 3
Output: true
Example 2:
5
/ \
1 4
/ \
3 6
Output: false
Explanation: The input is: [5,1,4,null,null,3,6]. The root node's value
is 5 but its right child's value is 4.
Reference Answer
思路分析
看到二叉树我们首先想到需要进行递归来解决问题。这道题递归的比较巧妙。让我们来看下面一棵树:
4
/ \
1 5
/ \
3 6
Output: false
Explanation: The input is: [5,1,4,null,null,3,6]. The root node's value
is 5 but its right child's value is 4.
对于这棵树而言,怎样进行递归呢?root.left这棵树的所有节点值都小于root,root.right这棵树的所有节点值都大于root。然后依次递归下去就可以了。例如:如果这棵树是二叉查找树,那么左子树的节点值一定处于(负无穷,4)这个范围内,右子树的节点值一定处于(4,正无穷)这个范围内。思路到这一步,程序就不难写了。
Reference Code
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def isValidBST(self, root):
"""
:type root: TreeNode
:rtype: bool
"""
if not root:
return True
return self.helper(root, float('-inf'), float('+inf'))
def helper(self, root, min_count, max_count):
if not root:
return True
if root.val <= min_count or root.val >= max_count:
return False
return self.helper(root.left, min_count, root.val) and self.helper(root.right, root.val, max_count)
C++ 版本
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
bool isValidBST(TreeNode* root) {
if (!root){
return true;
}
return helper(root, LONG_MIN, LONG_MAX);
}
bool helper(TreeNode* root, long min_count, long max_count){
if (!root){
return true;
}
if (root->val <= min_count || root->val >= max_count){
return false;
}
return helper(root->left, min_count, root->val) and helper(root->right, root->val, max_count);
}
};
Note:
- 这道题本想着中序遍历,判断是否顺序增长,但好像一直没有作通,还是改为与根节点进行比较判别吧。