Maximum Depth of Binary Tree
Maximum Depth of Binary Tree
Given a binary tree, find its maximum depth.
The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.
The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.
Solution - Recursion
The recursion algorithm is easy to come up:- Perform a DFS (depth-first search) on the tree and return the max depth.
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
private int dfs(TreeNode root) {
if (root == null) return 0;
return Math.max(dfs(root.left) + 1, dfs(root.right) + 1);
}
public int maxDepth(TreeNode root) {
return dfs(root);
}
This algorithm touch each node once and thus runs in time O(n), where n is the total number of nodes in the tree. It requires O(h) space for recursion, where h is the height of the tree.Solution - Iteration
This problem can also be solved iteratively.Here is a solution using BFS (breadth-first search).
public int maxDepth(TreeNode root) {
int len = 0;
LinkedList<TreeNode> que = new LinkedList<TreeNode>();
if (root != null) {
que.addLast(root);
que.addLast(null); // add a special node for level breaker
}
while (!que.isEmpty()) {
TreeNode cur = que.removeFirst();
if (cur == null) { // finish one level
++len;
if (!que.isEmpty()) que.addLast(null);
} else {
if (cur.left != null) que.addLast(cur.left);
if (cur.right != null) que.addLast(cur.right);
}
}
return len;
}
Similarly, this algorithm runs in time O(n). Since we keep all nodes in a level in the queue, in worst case, it requires O(n) spaces. (Think about a full binary tree with n/2 nodes at bottom level.)
浙公网安备 33010602011771号