Maximum Depth of Binary Tree 解答

时间:2022-09-04 13:23:31

Question

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.

Solution 1 -- Recursion

Recursion way is easy to think. Similar with "Minimum Depth of Binary Tree", time complexity is O(n).

 /**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public int maxDepth(TreeNode root) {
if (root == null)
return 0;
return Math.max(maxDepth(root.left), maxDepth(root.right)) + 1;
}
}

Solution 2 -- Iteration

BFS: We can still use level order traversal to get depth.

 /**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public int maxDepth(TreeNode root) {
if (root == null)
return 0;
List<TreeNode> current = new ArrayList<TreeNode>();
current.add(root);
List<TreeNode> next;
int result = 1;
while (current.size() > 0) {
next = new ArrayList<TreeNode>();
for (TreeNode tmpNode : current) {
if (tmpNode.left != null)
next.add(tmpNode.left);
if (tmpNode.right != null)
next.add(tmpNode.right);
}
current = next;
result++;
}
return result - 1;
}
}

DFS: Traverse tree while recording level number.

 # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None class Solution:
def maxDepth(self, root: TreeNode) -> int:
if not root:
return 0
node_stack = [root]
value_stack = [1]
result = 1
while node_stack:
node = node_stack.pop()
value = value_stack.pop()
result = max(value, result)
if node.left:
node_stack.append(node.left)
value_stack.append(value + 1)
if node.right:
node_stack.append(node.right)
value_stack.append(value + 1)
return result