LeetCode 98. Validate Binary Search Tree (有效二叉搜尋樹)
阿新 • • 發佈:2018-12-04
原題
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:
- 這道題本想著中序遍歷,判斷是否順序增長,但好像一直沒有作通,還是改為與根節點進行比較判別吧。