分析
难度 易
来源
https://leetcode.com/problems/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.
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 package LeetCode; 2 3 import java.util.*; 4 5 public class L110_BalancedBinaryTree { 6 public TreeNode makeBinaryTreeByArray(Integer[] array,int index){ 7 if(index<array.length&&array[index]!=null){ 8 int value=array[index]; 9 TreeNode t=new TreeNode(value); 10 array[index]=0; 11 t.left=makeBinaryTreeByArray(array,index*2+1); 12 t.right=makeBinaryTreeByArray(array,index*2+2); 13 return t; 14 }else 15 return null; 16 } 17 public int maxDepth(TreeNode root) {//获取深度的函数单独拆出 18 if(root==null) 19 return 0; 20 return Math.max(maxDepth(root.left),maxDepth(root.right))+1; 21 } 22 public boolean isBalanced(TreeNode root) { 23 if(root==null) 24 return true; 25 return (Math.abs(maxDepth(root.left)-maxDepth(root.right))<=1)&&isBalanced(root.left)&&isBalanced(root.right); 26 } 27 28 public void levelOrderTraversal(TreeNode root){//广度优先搜索+分层.注意非全二叉树插入空节点 29 if(root==null){ 30 return; 31 } 32 Queue<TreeNode> queue=new LinkedList<TreeNode>(); 33 queue.offer(root); 34 int curCount=1;//记录当前层节点数 35 int nextCount=0;//记录下一层节点数 36 int outCount=0;//记录出队列节点数 37 while(!queue.isEmpty()){ 38 TreeNode node=queue.poll(); 39 outCount++; 40 if(node!=null){ 41 System.out.print(node.val);//空节点无值打印,直接输出下方的tab 42 queue.offer(node.left); 43 nextCount++; 44 queue.offer(node.right); 45 nextCount++; 46 } 47 System.out.print(" "); 48 if(outCount==curCount)//当前层全部出队列 49 { 50 System.out.println(); 51 curCount=nextCount; 52 nextCount=0; 53 outCount=0; 54 } 55 } 56 } 57 public static void main(String[] args){ 58 L110_BalancedBinaryTree l110=new L110_BalancedBinaryTree(); 59 Integer[] nums={3,9,20,null,null,15,7}; 60 //Integer[] nums={1,2,2,3,3,null,null,4,4}; 61 TreeNode root=l110.makeBinaryTreeByArray(nums,0); 62 //l110.levelOrderTraversal(root); 63 System.out.println(l110.isBalanced(root)); 64 } 65 }