leetcode:balanced Binary Tree

Source: Internet
Author: User

Requirements: Determine whether a tree is a balanced binary tree

if  is height-The IS as in1

The code is as follows:

1 structTreeNode {2     intVal;3TreeNode *Left ;4TreeNode *Right ;5TreeNode (intx): Val (x), left (null), right (null) {}6 };7 8 intMaxtreedepth (TreeNode *root)//seek the depth of the tree first9 {Ten     if(NULL = =root) One         return 0; A     intLval = Maxtreedepth (root->Left ); -     intRval = Maxtreedepth (root->Right ); -     return 1+ (Lval > Rval?)lval:rval); the } - BOOLisbalanced (TreeNode *root)//Judging by the depth of the tree, whether it's a balance tree. - { -     if(NULL = =root) +         return true; -     intdiff = maxtreedepth (root->left)-Maxtreedepth (root->Right ); +     if(diff <-1|| Diff >1) A         return false; at     returnisbalanced (Root->left) && isbalanced (root->Right ); -}

leetcode:balanced Binary Tree

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.