Leetcode剑指Offer刷题指南:
解法一:递归DFS
class Solution {
public int maxDepth(TreeNode root) {
if (root == null) return 0;
int left = maxDepth(root.left);
int right = maxDepth(root.right);
return Math.max(left, right) + 1;
}
}
解法二:层序遍历(BFS)
class Solution {
public int maxDepth(TreeNode root) {
if (root == null) return 0;
Queue<TreeNode> queue = new LinkedList<>();
queue.add(root);
int count = 0;
while (!queue.isEmpty()) {
count++;
int n = queue.size();
for (int i = 0; i < n; ++i) {
TreeNode node = queue.poll();
if (node.left != null) {
queue.add(node.left);
}
if (node.right != null) {
queue.add(node.right);
}
}
}
return count;
}
}
解法:递归
class Solution {
public boolean isBalanced(TreeNode root) {
if (root == null) return true;
//左右子树有一个不平衡
if (!isBalanced(root.left) || !isBalanced(root.right)) return false;
//左右子树深度差大于1
if (Math.abs(depth(root.left) - depth(root.right)) > 1) return false;
return true;
}
public int depth(TreeNode root) {
return root == null ? 0 : Math.max(depth(root.left), depth(root.right)) + 1;
}
}