Leetcode----------Balanced Binary Tree

Source: Internet
Author: User

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.

Topic Balanced Binary Tree
Pass Rate 32.1%
Difficulty Easy

The question is whether it's a balanced binary tree.

Balanced binary Tree definition (AVL): It is either an empty tree or a two-fork tree with the following properties: The absolute value of the difference in the depth of the Saozi right subtree is not more than 1, and its Saozi right subtree is a balanced binary tree.

Key points: Depth-first traversal, recursion;

Our judgment process starts with the definition:

1. True if it is an empty tree;

2. If the tree is not empty, call the GetHeight () method, if it is a two-tree, this method returns the height of the tree, otherwise returns-1;

3. In the GetHeight () method, the left and right sub-trees are processed by the idea of recursion;

Java code:

/*** Definition for Binary tree * public class TreeNode {* Int. val; * TreeNode left; * TreeNode right; * TreeNode (int x) {val = x;} }*/ Public classSolution { Public Booleanisbalanced (TreeNode root) {if(root==NULL)return true; if(GetHeight (root) = =-1)return false; return true; }         Public intgetheight (TreeNode root) {if(Root = =NULL)return0; intleft =getheight (Root.left); intright =getheight (root.right); if(Left==-1 | | right==-1)return-1; if(Math.Abs (left-right) >1)return-1; returnMath.max (left,right) +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.