[Leetcode] [BST] [validate Binary Search Tree]

Source: Internet
Author: User

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 ..

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.