Leetcode 98 Validate Binary Search tree to determine whether it is a legal binary

Source: Internet
Author: User

1 /**2 * Definition for a binary tree node.3 * struct TreeNode {4 * int val;5 * TreeNode *left;6 * TreeNode *right;7 * TreeNode (int x): Val (x), left (null), right (null) {}8  * };9  */Ten classSolution { One  Public: A     BOOLLeft (treenode* left,introot) { -          while(Left->right! =NULL) { -left = left->Right ; the         } -         returnLeft->val <Root; -     } -     BOOLRight (treenode* right,introot) { +          while(Right->left! =NULL) -right = Right->Left ; +         returnRight->val >Root; A     } at      -     BOOLIsvalidbst (treenode*root) { -         if(Root = NULL)return true; -         intleft =0, right =0; -         BOOLLres =true, Rres =true; -         if(Root->left) {//Non-empty case inleft =1; -             if(Root->left->val >= Root->val)return false; toLres = Isvalidbst (root->Left ); +             if(lres) Lres = Left (root->left,root->val);//If the left son is a legitimate binary tree, test the maximum value of the left son (that is, always take the left son's right son) is less than the root value -             Else return false; the         } *         if(Root->right){ $right =1;Panax Notoginseng             if(Root->right->val <= Root->val)return false; -Rres = Isvalidbst (root->Right ); the             if(rres) Rres = right (root->right,root->val); +             Else return false; A         } the         returnLres &&Rres; +     } -      $};

Legal binary Tree conditions: 1, the left son are small root, the right son is greater than the root 2, the left son, the right son are legitimate binary tree

Leetcode 98 Validate Binary Search tree to determine whether it is a legal binary

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.