Category | Difficulty | Likes | Dislikes |
---|
algorithms | Medium (60.88%) | 391 | - |
Tags
tree
| breadth-first-search
Companies
amazon
| apple
| bloomberg
| facebook
| linkedin
| microsoft
给定一个二叉树,返回其按层次遍历的节点值。 (即逐层地,从左到右访问所有节点)。
例如:
给定二叉树: [3,9,20,null,null,15,7]
,
1
2
3
4
5
| 3
/ \
9 20
/ \
15 7
|
返回其层次遍历结果:
1
2
3
4
5
| [
[3],
[9,20],
[15,7]
]
|
Discussion | Solution
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
| /**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<vector<int>> levelOrder(TreeNode* root) {
vector<vector<int>> res;
if (!root){
return res;
}
queue<TreeNode*> q; //queue for treenode which vist with inorder
// init queue with root
q.push(root);
q.push(NULL); // level flag
vector<int> cur_level; //
while(!q.empty()){
// deque
auto n = q.front(); q.pop();
if(n) {
cur_level.push_back(n->val);
if(n->left){
q.push(n->left);
}
if(n->right){
q.push(n->right);
}
} else {
res.push_back(cur_level); cur_level.resize(0);
if(q.size()>0){
q.push(NULL);
}
}
}
return res;
}
};
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
| // @lc code=start
// Definition for a binary tree node.
// #[derive(Debug, PartialEq, Eq)]
// pub struct TreeNode {
// pub val: i32,
// pub left: Option<Rc<RefCell<TreeNode>>>,
// pub right: Option<Rc<RefCell<TreeNode>>>,
// }
//
// impl TreeNode {
// #[inline]
// pub fn new(val: i32) -> Self {
// TreeNode {
// val,
// left: None,
// right: None
// }
// }
// }
use std::cell::RefCell;
use std::collections::VecDeque;
use std::rc::Rc;
impl Solution {
/// ## 解题思路
/// - 队列
pub fn level_order(root: Option<Rc<RefCell<TreeNode>>>) -> Vec<Vec<i32>> {
let mut res = Vec::new(); //result
let mut q = VecDeque::new();
root.map(|root| {
q.push_back(root.clone());
while !q.is_empty() {
let mut cur_level_vals = Vec::new();
for _ in 0..q.len() {
if let Some(node) = q.pop_front() {
cur_level_vals.push(node.borrow().val);
node.borrow().left.clone().map(|left| {
q.push_back(left);
});
node.borrow().right.clone().map(|right| {
q.push_back(right);
});
}
}
res.push(cur_level_vals);
}
});
res
}
}
// @lc code=end
|