每日一题做题记录,参考官方和三叶的题解 |
题目要求
思路一:DFS
- 维护一个当前最大深度,来找最深最左的值。
Java
class Solution {
int depth = 0, res;
public int findBottomLeftValue(TreeNode root) {
DFS(root, 1);
return res;
}
void DFS(TreeNode root, int cur) {
if (root == null)
return ;
if (cur > depth) {
depth = cur; // 记录最大深度
res = root.val;
}
DFS(root.left, cur + 1);
DFS(root.right, cur + 1);
}
}
- 时间复杂度: O ( n ) O(n) O(n)
- 空间复杂度: O ( n ) O(n) O(n),最坏情况下退化成链,递归深度为 n n n。
C++
class Solution {
public:
int depth = 0, res;
int findBottomLeftValue(TreeNode* root) {
DFS(root, 1);
return res;
}
void DFS(TreeNode* root, int cur) {
if (root == nullptr)
return ;
if (cur > depth) {
depth = cur;
res = root->val;
}
DFS(root->left, cur + 1);
DFS(root->right, cur + 1);
}
};
- 时间复杂度: O ( n ) O(n) O(n)
- 空间复杂度: O ( n ) O(n) O(n),最坏情况下退化成链,递归深度为 n n n。
Rust
这里各种变量判空以及unwrap
、borrow
来回拉扯没有写出来,之后认真学了Rust再说……
思路二:BFS
- 维护一个队列依次遍历,当前层的第一个节点就是最左节点。
Java
class Solution {
public int findBottomLeftValue(TreeNode root) {
Deque<TreeNode> que = new ArrayDeque<>();
que.addLast(root);
int res = 0;
while (!que.isEmpty()) {
res = que.peek().val;
int len = que.size();
while (len-- > 0) {
TreeNode top = que.pollFirst();
if (top.left != null)
que.addLast(top.left);
if (top.right != null)
que.addLast(top.right);
}
}
return res;
}
}
- 时间复杂度: O ( n ) O(n) O(n)
- 空间复杂度: O ( n ) O(n) O(n),最坏情况下所有节点都在同一层
C++
class Solution {
public:
int findBottomLeftValue(TreeNode* root) {
queue<TreeNode*> que;
que.push(root);
int res = 0;
while (!que.empty()) {
res = que.front()->val;
int len = que.size();
while (len-- > 0) {
TreeNode* top = que.front();
que.pop();
if (top->left != nullptr)
que.push(top->left);
if (top->right != nullptr)
que.push(top->right);
}
}
return res;
}
};
- 时间复杂度: O ( n ) O(n) O(n)
- 空间复杂度: O ( n ) O(n) O(n),最坏情况下所有节点都在同一层
Rust
use std::rc::Rc;
use std::cell::RefCell;
impl Solution {
pub fn find_bottom_left_value(root: Option<Rc<RefCell<TreeNode>>>) -> i32 {
let mut que = vec![root.unwrap()];
let mut res = 0;
while que.len() > 0 {
let mut tmp = vec![];
que.iter().enumerate().for_each(|(i, cur)| {
if i == 0 {
res = cur.borrow().val;
}
if let Some(left) = cur.borrow().left.clone() {
tmp.push(left);
}
if let Some(right) = cur.borrow().right.clone() {
tmp.push(right);
}
});
que = tmp;
}
res
}
}
- 时间复杂度: O ( n ) O(n) O(n)
- 空间复杂度: O ( n ) O(n) O(n),最坏情况下所有节点都在同一层
总结
快乐遍历,其实第一反应是深度优先,毕竟找最深的那个,看了题解意识到对于找最深BFS反而更好用,不用去维护当前最大深度。
【Rust的各种变量类型balabala好麻烦嘤嘤嘤】
欢迎指正与讨论! |