Programmer interview guide checks whether it is BST or not.

Source: Internet
Author: User

Programmer interview guide checks whether it is BST or not.

[Disclaimer: All Rights Reserved. indicate the source for reprinting. Do not use it for commercial purposes. Contact mailbox: libin493073668@sina.com]


Question link: http://www.nowcoder.com/practice/536c0199151245f897da2c5390930657? Rp = 1 & ru =/ta/cracking-the-coding-interview & qru =/ta/cracking-the-coding-interview/question-ranking


Description
Implement a function to check whether a binary tree is a binary search tree.
For the given tree's root node pointer TreeNode * root, please return a bool, which indicates whether the tree is a binary search tree.

Ideas
We only need to judge whether the left node, right node, and parent node meet the law of the binary search tree when searching down.


/*struct TreeNode {    int val;    struct TreeNode *left;    struct TreeNode *right;    TreeNode(int x) :            val(x), left(NULL), right(NULL) {    }};*/class Checker{public:bool checkBST(TreeNode *root){// write code herereturn isBST(root);}bool isBST(TreeNode *root){if(root==nullptr)return true;bool left = true,right=true;if(root->left && root->left->val>root->val)return false;if(root->right && root->right->val<root->val)return false;if(root->left)left = isBST(root->left);if(root->right)right = isBST(root->right);return left && right;}};


Copyright Disclaimer: This article is the original article of the blogger. If it is reproduced, please indicate the source

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.