|
|
@ -236,3 +236,59 @@ class Solution { |
|
|
|
} |
|
|
|
} |
|
|
|
``` |
|
|
|
``` |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
#### [55 - II. 平衡二叉树](https://leetcode-cn.com/problems/ping-heng-er-cha-shu-lcof/) |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
```java |
|
|
|
|
|
|
|
class Solution { |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
public boolean isBalanced(TreeNode root) { |
|
|
|
|
|
|
|
if (root == null) { |
|
|
|
|
|
|
|
return true; |
|
|
|
|
|
|
|
} |
|
|
|
|
|
|
|
Deque<TreeNode> queue = new LinkedList<>(); |
|
|
|
|
|
|
|
queue.add(root); |
|
|
|
|
|
|
|
while (!queue.isEmpty()) { |
|
|
|
|
|
|
|
TreeNode node = queue.poll(); |
|
|
|
|
|
|
|
int offset = Math.abs(maxDepth(node.left) - maxDepth(node.right)); |
|
|
|
|
|
|
|
if (offset > 1) { |
|
|
|
|
|
|
|
return false; |
|
|
|
|
|
|
|
} |
|
|
|
|
|
|
|
if (node.left != null) { |
|
|
|
|
|
|
|
queue.add(node.left); |
|
|
|
|
|
|
|
} |
|
|
|
|
|
|
|
if (node.right != null) { |
|
|
|
|
|
|
|
queue.add(node.right); |
|
|
|
|
|
|
|
} |
|
|
|
|
|
|
|
} |
|
|
|
|
|
|
|
return true; |
|
|
|
|
|
|
|
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
private int maxDepth(TreeNode root) { |
|
|
|
|
|
|
|
if (root == null) { |
|
|
|
|
|
|
|
return 0; |
|
|
|
|
|
|
|
} |
|
|
|
|
|
|
|
return Math.max(maxDepth(root.left), maxDepth(root.right)) + 1; |
|
|
|
|
|
|
|
} |
|
|
|
|
|
|
|
} |
|
|
|
|
|
|
|
``` |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
```java |
|
|
|
|
|
|
|
class Solution { |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
public boolean isBalanced(TreeNode root) { |
|
|
|
|
|
|
|
if (root == null) { |
|
|
|
|
|
|
|
return true; |
|
|
|
|
|
|
|
} |
|
|
|
|
|
|
|
return Math.abs(maxDepth(root.left) - maxDepth(root.right)) <= 1 && isBalanced(root.left) && isBalanced( |
|
|
|
|
|
|
|
root.right); |
|
|
|
|
|
|
|
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
private int maxDepth(TreeNode root) { |
|
|
|
|
|
|
|
if (root == null) { |
|
|
|
|
|
|
|
return 0; |
|
|
|
|
|
|
|
} |
|
|
|
|
|
|
|
return Math.max(maxDepth(root.left), maxDepth(root.right)) + 1; |
|
|
|
|
|
|
|
} |
|
|
|
|
|
|
|
} |
|
|
|
|
|
|
|
``` |
|
|
|
|
|
|
|
|
|
|
|