Leetcode513. 找树左下角的值 Find Bottom Left Tree Value(Java)
##Tree##, ##Depth-first Search##, ##Breadth-first Search##
找树左下角的值,即找最底下一层的最左边结点
本题深度优先搜索、广度优先搜索都可以解决
BFS使用队列,每次循环每一层,记录每一层的最左边结点,最后返回的即为最底下一层的最左边结点
DFS函数需要维护当前深度depth
和已经遍历过的最大深度count
,当前深度depth
大于已遍历过的最大深度count
时,考虑更新结果值
保证先遍历左子树,再遍历右子树,保证每次遍历的第一个depth > count
的结点都是深度为depth
层的最左边结点
**时间复杂度:**DFS:O(n), BFS:O(n)
DFS
class Solution {
int depth = 1;
int res = 0;
public int findBottomLeftValue(TreeNode root) {
if (root == null) return 0;
res = root.val;
dfs(root, depth);
return res;
}
public void dfs(TreeNode root, int count) {
if (root == null) return;
if (count > depth) {
res = root.val;
depth = count;
}
if (root.left != null) dfs(root.left, count + 1);
if (root.right != null) dfs(root.right, count + 1);
}
}
BFS
class Solution {
int res = 0;
public int findBottomLeftValue(TreeNode root) {
if (root == null) return 0;
res = root.val;
bfs(root);
return res;
}
public void bfs(TreeNode root) {
Queue<TreeNode> q = new LinkedList<TreeNode>();
q.add(root);
while (!q.isEmpty()) {
int n = q.size();
res = q.peek().val;
for (int i = 0; i < n; i++) {
TreeNode t = q.poll();
if (t.left != null) q.add(t.left);
if (t.right != null) q.add(t.right);
}
}
}
}