// 递归
public int maxDepth(TreeNode root) {
if (root == null) {
return 0;
}
int leftDepth = maxDepth(root.left);
int rightDepth = maxDepth(root.right);
return Math.max(leftDepth, rightDepth) + 1;
}
// 迭代 -- 效率低一些
public int maxDepth2(TreeNode root) {
if (root == null) {
return 0;
}
Queue<Pair<TreeNode, Integer>> queue = new LinkedList<>();
queue.add(new Pair(root, 1));
int depth = 0;
while (!queue.isEmpty()) {
Pair<TreeNode, Integer> current = queue.poll();
root = current.fst;
int currentDepth = current.snd;
if (root != null) {
depth = Math.max(depth, currentDepth);
queue.add(new Pair(root.left, currentDepth + 1));
queue.add(new Pair(root.right, currentDepth + 1));
}
}
return depth;
}
网友评论