Thinking process I - Divide and Conquer
- what is the maximum depth of left subtree?
- what is the maximum depth of right subtree?
- get the bigger one and then plus 1, is the maximum depth at current node
O(n)
public class Solution {
/**
* @param root: The root of binary tree.
* @return: An integer.
*/
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;
}
}
Thinking process II - Traversal
Specifically, this is pre-order traversal
public class Solution {
/**
* @param root: The root of binary tree.
* @return: An integer.
*/
private int depth;
public int maxDepth(TreeNode root) {
depth = 0;
dfsHelper(root, 0);
return depth;
}
private void dfsHelper(TreeNode node, int currDepth) {
if (node == null) {
return;
}
currDepth += 1;
depth = Math.max(currDepth, depth);
dfsHelper(node.left, currDepth);
dfsHelper(node.right, currDepth);
}
}