127.Balanced Binary Tree
题目:
Given a binary tree, determine if it is height-balanced.
给定二叉树,确定它是否是高度平衡的。
For this problem, a height-balanced binary tree is defined as:
对于此问题,高度平衡二叉树定义为:
a binary tree in which the depth of the two subtrees of every node never differ by more than 1.
一个二叉树,其中每个节点的两个子树的深度从不相差超过1。
Example 1:
Given the following tree [3,9,20,null,null,15,7]
:
3 / \ 9 20 / \ 15 7
Return true.
Example 2:
Given the following tree [1,2,2,3,3,null,null,4,4]
:
1 / \ 2 2 / \ 3 3 / \ 4 4
Return false.
解答:
1 /** 2 * Definition for a binary tree node. 3 * public class TreeNode { 4 * int val; 5 * TreeNode left; 6 * TreeNode right; 7 * TreeNode(int x) { val = x; } 8 * } 9 */ 10 class Solution { 11 public boolean isBalanced(TreeNode root) { 12 if(root==null) 13 return true; 14 return height(root)!=-1; 15 } 16 17 public int height(TreeNode node){ 18 if(node==null) 19 return 0; 20 int lH=height(node.left); 21 if(lH==-1) 22 return -1; 23 int rH=height(node.right); 24 if(rH==-1) 25 return -1; 26 if(lH-rH<-1||lH-rH>1) 27 return -1; 28 return Math.max(lH,rH)+1; 29 } 30 }
详解:
1.空树或只有根节点均为高度平衡的二叉树
2.如果左-右=0,-1,1均为高度平衡的二叉树,返回树的高度(左子树和右子树高度较大值+1)
3.如果左-右<-1或左-右>1,则不是高度平衡的二叉树,直接返回-1