104.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.
Subscribe to see which companies asked this question.
给定一棵两叉树,求它的最大深度。
递归求解,递归公式
f(n) = 0; n=null,
f(n) = 1+ max(f(n左), f(n右))
public class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) {
val = x;
}
}
public int maxDepth(TreeNode root) {
if (root == null)
return 0;
int leftDepth = maxDepth(root.left);
int rightDepth = maxDepth(root.right);
//左右子树的深度+1跟节点,为总深度
return (leftDepth > rightDepth) ? (leftDepth + 1) : (rightDepth + 1);
}
111.Minimum Depth of Binary Tree
Given a binary tree, find its minimum depth.
The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node.
注意点在于如果某个根节点有一边的子树为空,那么它的深度就等于另一边不为空的子树的深度,其他的逻辑与上一题相同。
递归
public int minDepth(TreeNode root) {
if (root == null)
return 0;
// 左空,右不空
if (root.left == null && root.right != null)
// 返回右子树深度
return minDepth(root.right) + 1;
// 右空,左不空
if (root.right == null && root.left != null)
// 返回左子树深度
return minDepth(root.left) + 1;
// 否则返回左右子树的最小深度
int leftmin = minDepth(root.left);
int rightmin = minDepth(root.right);
return Math.min(leftmin, rightmin) + 1;
}
public int minDepth(TreeNode root) {
if (root == null)
return 0;
else {
// 都不是空,返回最小值
if (root.left != null && root.right != null)
// 注意+1根节点深度
return 1 + Math.min(minDepth(root.left)
, minDepth(root.right));
else
// 有一个为空,则选择另外一个高度。此时有一个深度为0;
return 1 + minDepth(root.left) + minDepth(root.right);
}
}
层次遍历
记录层数,当到达第一个叶结点时候就是最小深度
public int minDepth(TreeNode root) {
if (root == null)
return 0;
Queue<TreeNode> q = new LinkedList<>();
// 使用map记录当前所处层数
HashMap<TreeNode, Integer> map = new HashMap<>();
q.offer(root);
// 跟结点第一层
map.put(root, 1);
List<Integer> tmp = new ArrayList<>();
while (!q.isEmpty()) {
TreeNode node = q.poll();
int curLevel = map.get(node);
// 第一个到达左右子树为空的结点就是最低深度
if (node.left == null && node.right == null)
return curLevel;
tmp.add(node.val);
if (node.left != null) {
q.offer(node.left);
map.put(node.left, curLevel + 1);
}
if (node.right != null) {
q.offer(node.right);
map.put(node.right, curLevel + 1);
}
}
return 0;
}