문제요약:
Given the root of a binary tree, return the level order traversal of node values.
(left to right, root to leaf, level by level).
제약:
num of nodes in the tree [0,2000]
-1000 <= Node.val <= 1000
예제 1 입력. | 예제 1 출력. |
root = [3,9,20,null,null,15,7] | [[3],[9,20],[15,7]] |
예제 2 입력. | 예제 2 출력. |
root = [1] | [[1]] |
예제 3 입력. | 예제 3 출력. |
root = [] | [] |
정답코드:
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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
|
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
vector<vector<int>> levelOrder(TreeNode* root) {
vector<vector<int>> vector;
vector = BFS_Traverse(vector, root);
return vector;
}
vector<vector<int>> BFS_Traverse(vector<vector<int>> v, TreeNode *node){
// Queue {Node, level} for BFS
queue <pair<TreeNode*,int>> Q;
TreeNode* curNode = NULL;
int leftVal, rightVal;
int level = 0;
// Push root to the queue.
Q.push(make_pair(node, level));
while (Q.empty() == false)
{
curNode = Q.front().first;
level = Q.front().second;
Q.pop();
if (curNode == NULL)
{
// If empty node, continue
continue;
}
else
{
// Create new vector for new level if the level is first touched.
if (v.size() == level)
{
vector <int> levelVec;
levelVec.push_back(curNode->val);
v.push_back(levelVec);
}
else
{
v[level].push_back(curNode->val);
}
}
if (curNode->left != NULL)
{
// push left node to the queue with level+1 value.
leftVal = curNode->left->val;
Q.push(make_pair(curNode->left, level+1));
}
if (curNode->right != NULL)
{
// push right node to the queue with level+1 value.
rightVal = curNode->right->val;
Q.push(make_pair(curNode->right, level+1));
}
}
return v;
}
};
|
cs |
원본 링크: https://leetcode.com/problems/binary-tree-level-order-traversal/
'알고리즘 문제풀이' 카테고리의 다른 글
[알고리즘] LeetCode 49번 "Group Anagrams" (C/C++) - Don 임베디드 (0) | 2022.11.05 |
---|---|
[알고리즘] LeetCode 703번 "Kth Largest Element in a Stream" (C/C++) - Don 임베디드 (0) | 2022.10.21 |
[알고리즘] LeetCode 268번 "Missing Number" (C/C++) - Don 임베디드 (0) | 2022.10.05 |
[알고리즘] LeetCode 252번 "Meeting Rooms" (C/C++) - Don 임베디드 (0) | 2022.09.30 |
[알고리즘] LeetCode 66번 "Plus One" (C/C++) - Don 임베디드 (0) | 2022.09.29 |