本题可以使用深搜或者广搜来解决. 对于一个思想或者方法, 一定要思考得深入一点, 如果下次知道这个解法, 但是没有写出来, 那么就说明是因为没有深入思考.
BFS
广搜和二叉树的结合, 一个典型的例子就是层次打印二叉树. 一般来说, 使用一个队列来完成遍历, 这里要求的是最左边的值. 因为先入队的先出队, 所以在加入队列的时候, 先加入其右节点, 再加入其左节点. 这样最后出队的肯定是最低层, 最左边的节点.
class Solution {
public int findBottomLeftValue(TreeNode root) {
if (root == null) return 0;
return dfs(root);
}
public int dfs(TreeNode root) {
Queue<TreeNode> queue = new LinkedList<>();
queue.add(root);
TreeNode temp = null;
while(queue.size() > 0) {
temp = queue.poll();
if (temp.right != null) queue.add(temp.right);
if (temp.left != null) queue.add(temp.left);
}
return temp.val;
}
}
DFS
用一个长度为 2 的数组存储结果, result[0] 表示对应的节点的值, result[1] 表示对应的深度.
class Solution {
// result[0] 表示节点的值 result[1] 表示节点的深度
int[] result = new int[]{0, -1};
public int findBottomLeftValue(TreeNode root) {
dfs(root, 0);
return result[0];
}
public void dfs(TreeNode root, int depth) {
if (root == null) return;
if (depth > result[1]) {
result[0] = root.val;
result[1] = depth;
}
dfs(root.left, depth + 1);
dfs(root.right, depth + 1);
}
}
后面还会有 DFS 和 BFS 的相关题目.