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.
Idea: Judging whether it is a balanced binary tree, DFS can, recursively determine whether each sub-tree is balanced binary tree, if there are sub-tree is not satisfied, the whole is not satisfied.
The specific code is as follows:
/** * Definition for a binary tree node. * public class TreeNode {* int val, * TreeNode left, * TreeNode right; * TreeNode (int x) {val = x;} *} */public class Solution { /** * Determine if the binary tree is balanced * see if the height difference between the left and right subtree is more than 1 * not more than 1 respectively determine whether the left and right sub-tree balance binary tree */Public Boolean isbalanced (TreeNode root) { if (root = null) return true; if (DEP (0,root) >-Ten) return true; return false; } Height of the calculation tree private int dep (int dep,treenode root) { if (root = null) { return dep-1; } int dep1 = DEP (dep+1,root.left); int DEP2 = DEP (dep+1,root.right); If the height difference exceeds 1, return -10 //The subsequent DEP return value will be -10 if (Math.Abs (DEP1-DEP2) > 1) { return-10; } Return dep1 > Dep2? DEP1:DEP2;} }
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Leetcode 110.Balanced binary tree (balanced binary trees) ideas and methods of solving problems