Judge whether a tree is a binary search tree. It is a very classic-based algorithm.
When I first did this for a long time ago, I first obtained the result of the pre-order traversal of the tree, then determined whether the array was sorted in the same order as before, and determined whether the repeated Xiami was also made, A very tangled approach.
Later, I thought about how to use recursion. I thought that the maximum and minimum values of the two subtree should be returned according to the definition. I wrote the code for a while and found it troublesome and not right.
After looking at the problem, we found that we used a reverse thinking to pass the upper and lower circles down from the top of the tree, rather than the bottom-up constraints. The author is too witty.
1 /** 2 * Definition for binary tree 3 * struct TreeNode { 4 * int val; 5 * TreeNode *left; 6 * TreeNode *right; 7 * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 * }; 9 */10 class Solution {11 public:12 bool validate(TreeNode *root, int low, int high) {13 if (root == NULL) {14 return true;15 }16 if (root->val <= low || root->val >= high) {17 return false;18 }19 return validate(root->left, low, root->val) 20 && validate(root->right, root->val, high);21 }22 bool isValidBST(TreeNode *root) {23 if (root == NULL) {24 return true;25 } 26 return validate(root, INT_MIN, INT_MAX);27 }28 };
There are two wa requests in the middle. One is because false is returned for the empty tree, and the other is because the Val is not removed.
Tree problems, think clearly can soon write code, and once AC. If you have no idea, you can easily wrap yourself in .. Status is very important ..