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.
思路:
这题其实考查的是BST的定义,下面code的是CC150v5上的第一种答案简化版,同样借鉴中序遍历的思想,但是只保存当前点上家的值,判断当前点是否大于上家。
代码:
1 bool isValidBST(TreeNode *root) { 2 int init = INT_MIN; 3 return isValidNode(root, init); 4 } 5 bool isValidNode(TreeNode *root, int& lastVal){ 6 if(root == NULL) 7 return true; 8 9 if(!isValidNode(root->left, lastVal)) 10 return false; 11 12 if(root->val <= lastVal) //不是<而是<=,failed {1,1}=>false 13 return false; 14 lastVal = root->val; 15 16 if(!isValidNode(root->right, lastVal)) 17 return false; 18 19 return true;//忘写最后一句了 20 }