LeetCode:Validate Binary Search Tree(驗證二叉搜尋樹)
阿新 • • 發佈:2018-12-24
題目
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.
思路
學習大神的想法,採用遞迴的方法求解思路比較簡單。對於一個節點,其值一定大於他的左子樹的所有值,小於他的右子樹的所有值,可以發現,該節點的值可以作為左子樹的最大值,右子樹的最小值。
利用該性質編寫程式碼,在每次遍歷中,用節點的值替代左子樹的最大值和右子樹的最小值。對於根節點,最小值和最大值分別為LONG_MIN和LONG_MAX。
程式碼
/**
* 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) {
return isValidBST(root,LONG_MIN,LONG_MAX);
}
bool isValidBST(TreeNode* root, long min, long max)
{
if(!root)
return true;
if(root->val<=min||root->val>=max)
return false;
return isValidBST(root->left,min,root->val)&&isValidBST(root->right,root->val,max);
}
};