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