LeetCode :: Validate Binary Search Tree[詳細分析],leetcodevalidate
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.
回顧一下BST的定義,任一節點的子孫分別遞迴滿足,左子孫小於該節點,右子孫大於該節點;只要判斷這個就OK了;一個主意點:在遞迴程式裡面,僅判斷一個節點大於左兒子小於右兒子是不夠的,這樣對於左兒子的右兒子以及右兒子的左兒子的錯誤判斷不到,因此需要將節點值變為邊界值,遞迴下傳;代碼如下:
class Solution {public: bool isValidBST(TreeNode *root) { return check(root, INT_MIN, INT_MAX); } private: bool check(TreeNode *root, int left, int right){ if(root == NULL) return true; return (root->val > left) && (root->val < right) && check(root->left, left, root->val) &&check(root->right, root->val, right); }//這裡的左兒子的左界用上面傳下來的,右界用節點值,右兒子鏡面對稱};
PS:按照注意點提到的思路寫的錯誤碼
/** * 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) { if (root == NULL) return true; bool bleft = true, bright = true; if (root->left != NULL){ if (root->val > root->left->val){ //注意這裡檢驗以及遞迴是不能保證根節點大於左邊所有的,矛盾在於,左兒子的右兒子,以及右兒子的左兒子; bleft = isValidBST(root->left); } else{ return false; } } if (root->right != NULL){ if (root->val < root->right->val){ bright = isValidBST(root->right); } else{ return false; } } return bleft && bright; }};