问题描述
- 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. - Note: A leaf is a node with no children.
Example:
Given binary tree [3,9,20,null,null,15,7],3
/ \
9 20
/ \
15 7
return its depth = 3.
问题分析
- 求二叉树最大深度:二叉树经典套路解法:DFS递归
- 方法二三也提供了不用递归的解法:
- 方法2 : 先序遍历的非递归实现,一个栈存节点,另一个栈存相应节点所处的深度。所以也可以不用两个栈,直接用将节点与其所处高度封装成一个对象,放入一个栈即可。
- 方法2: 层序遍历 BFS
代码实现
- 方法1 : DFS递归
public int maxDepth(TreeNode root) {
if (root == null) {
return 0;
}
return 1 + Math.max(maxDepth(root.left), maxDepth(root.right));
}
- 方法2: 先序遍历非递归
public int maxDepth(TreeNode root) {
if (root == null) {
return 0;
}
Stack<TreeNode> nodeStack = new Stack<>();
Stack<Integer> depthStack = new Stack<>();
int maxDepth = 0;
nodeStack.add(root);
depthStack.add(1);
while (! nodeStack.isEmpty()) {
TreeNode popNode = nodeStack.pop();
int curDepth = depthStack.pop();
maxDepth = Math.max(maxDepth, curDepth);
if (popNode.right != null) {
nodeStack.add(popNode.right);
depthStack.add(curDepth + 1);
}
if (popNode.left != null) {
nodeStack.add(popNode.left);
depthStack.add(curDepth + 1);
}
}
return maxDepth;
}
- 方法3:层序遍历BFS
public int maxDepth(TreeNode root) {
if (root == null) {
return 0;
}
LinkedList<TreeNode> queue = new LinkedList<>();
queue.add(root);
int maxDepth = 0;
while(! queue.isEmpty()) {
int levelSize = queue.size();
for (int i = 0; i < levelSize; ++i) {
TreeNode popNode = queue.poll();
if (popNode.left != null) {
queue.add(popNode.left);
}
if (popNode.right != null) {
queue.add(popNode.right);
}
}
++maxDepth;
}
return maxDepth;
}