求二叉树的最大深度
递归实现
public int maxDepth(TreeNode root) {
if (root == null) {
return 0;
} else {
int leftHeight = maxDepth(root.left);
int rightHeight = maxDepth(root.right);
return Math.max(leftHeight, rightHeight) + 1;
}
}
bfs实现
public int maxDepth2(TreeNode root) {
int res = 0;
LinkedList<TreeNode> linkedList = new LinkedList<>();
if (root == null) return res;
linkedList.addLast(root);
while (linkedList.size() > 0) {
int size = linkedList.size();
for (int i = 0; i < size; i++) {
TreeNode first = linkedList.removeFirst();
if (first.left != null) {
linkedList.addLast(first.left);
}
if (first.right != null) {
linkedList.addLast(first.right);
}
}
res++;
}
return res;
}