110. Balanced Binary Tree
这道题重点是要明白平衡二叉树的定义。题目中给出的定义就是左右子树的高度不超过一。 参考了以下链接:
https://blog.csdn.net/DERRANTCM/article/details/47414041
代码如下:
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
12 public boolean isBalanced(TreeNode root) {
13
14 if(root == null){
15 return true;
16 }
17
18 int left = depth(root.left);
19 int right = depth(root.right);
20
21 if( Math.abs(left - right ) > 1){
22 return false;
23 }else{
24 return isBalanced(root.left) && isBalanced(root.right);
25 }
26 }
27
28 private int depth(TreeNode n){
29 if( n == null){
30 return 0;
31 }
32
33 if (n.left == null && n.right == null) {
34 return 1;
35 } else {
36 int left = depth(n.left);
37 int right = depth(n.right);
38 return 1 + (left > right ? left : right);
39 }
40 }
41
42
43 }
END