LeetCode110 blanced Binary Tree Java

Source: Internet
Author: User

Topic:

Given a binary tree, determine if it is height-balanced.

For this problem, a height-balanced binary tree was defined as a binary tree in which the depth of the Every node never differ by more than 1.


Exercises

To determine whether a binary tree is a balanced binary tree, the balanced binary tree is each node satisfies the height difference of the left and right sub-tree is less than 1

By calculating the left and right height difference of each node, the return value is set to 1 if the node is found to be unsatisfied (left==-1) return-1;
The IF (right==-1) return-1 guarantees that the final return result of a height difference of 1 will necessarily be-1, meaning that the return value is not-1 to determine whether the binary tree is balanced


Code:

public static Boolean isbalanced (TreeNode root) {if (Treehight (root) ==-1) return false;else return true;            public static int treehight (TreeNode root) {if (root==null) return 0;else {int left=treehight (root.left); int right= Treehight (root.right); if (left==-1) return-1;if (right==-1) return-1;if (Math.Abs (left-right) >1) Return-1;else { Return 1+math.max (Treehight (Root.left), Treehight (Root.right));}}}


Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

LeetCode110 blanced Binary Tree Java

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.