leetcode-balanced-binary-tree

题目大意

  https://leetcode.com/problems/balanced-binary-tree/

  判断一颗二叉树是否为平衡二叉树

题目分析

  了解平衡二叉树的定义以后利用递归就可以了。

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
private int getDepth(TreeNode root) {
if (root == null) {
return 0;
}
return Math.max(getDepth(root.left), getDepth(root.right)) + 1;
}
public boolean isBalanced(TreeNode root) {
if (root == null) {
return true;
}
return Math.abs(getDepth(root.left) - getDepth(root.right)) <= 1 && isBalanced(root.left) && isBalanced(root.right);
}
}