Binary Tree Balance Check

Source: Internet
Author: User

Implement a function to check whether the two fork tree is balanced, the balance is defined as follows, for any node in the tree, its two sub-tree height difference of not more than 1. Given a pointer to the root node treenode* root, return a bool, representing whether the tree is balanced.

ImportJava.util.*;/*Public class TreeNode {int val = 0;    TreeNode left = null;    TreeNode right = null;    Public TreeNode (int val) {this.val = val; }}*/ Public classBalance { Public Booleanisbalance (TreeNode root) {if(Root = =NULL){            return true; }                intLheight =treeheight (Root.left); intRheight =treeheight (root.right); if(lheight-rheight <= 1 && lheight-rheight >=-1){            returnIsbalance (Root.left) &&isbalance (root.right); }                return false; }         Public inttreeheight (TreeNode root) {if(Root = =NULL){            return0; }                intLheight =treeheight (Root.left); intRheight =treeheight (root.right); returnLheight > Rheight? Lheight + 1:rheight + 1; }}

Binary Tree Balance Check

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.