leetcode:balanced binary Tree

Source: Internet
Author: User

This problem is not very difficult, and the balance of the binary tree (AVL) Judgment method:

1. Determine if the difference between Zuozi height and right subtree height is less than 1

2. Determine if the root node Zuozi meets the balanced two forks

3. Determine if the right subtree of the root node satisfies the balance of two forks

The AVL tree satisfies the above three conditions

1 /**2 * Definition for binary tree3 * 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     BOOLisbalanced (TreeNode *root) { -         if(Root==null)return true; -         if(Root->left==null && Root->right==null)return true; the         if(ABS (GetHeight (Root->left)-getheight (root->right)) >1)return false; -         returnisbalanced (Root->left) && isbalanced (root->Right ); -     } -     intGetHeight (TreeNode *node) { +         if(Node==null)return 0; -         Else +         { A             intI=getheight (node->Left ); at             intJ=getheight (node->Right ); -             returni>j?i+1: j+1; -         } -          -     } -};

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.