-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path102.binary-tree-level-order-traversal.cpp
More file actions
112 lines (107 loc) · 2.63 KB
/
102.binary-tree-level-order-traversal.cpp
File metadata and controls
112 lines (107 loc) · 2.63 KB
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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
/*
* @lc app=leetcode id=102 lang=cpp
*
* [102] Binary Tree Level Order Traversal
*
* https://leetcode.com/problems/binary-tree-level-order-traversal/description/
*
* algorithms
* Medium (56.08%)
* Likes: 4199
* Dislikes: 102
* Total Accepted: 772.1K
* Total Submissions: 1.4M
* Testcase Example: '[3,9,20,null,null,15,7]'
*
* Given a binary tree, return the level order traversal of its nodes' values.
* (ie, from left to right, level by level).
*
*
* For example:
* Given binary tree [3,9,20,null,null,15,7],
*
* 3
* / \
* 9 20
* / \
* 15 7
*
*
*
* return its level order traversal as:
*
* [
* [3],
* [9,20],
* [15,7]
* ]
*
*
*/
// @lc code=start
/**
* 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) {
if (root == nullptr)
return vector<vector<int>>();
queue<TreeNode*> que;
que.push(root);
vector<vector<int>> res;
while (!que.empty()) {
vector<int> curLevel;
int size = que.size();
for (int i = 0; i < size; ++i) {
TreeNode* cur = que.front();
que.pop();
curLevel.push_back(cur->val);
if (cur->left)
que.push(cur->left);
if (cur->right)
que.push(cur->right);
}
if (size > 0)
res.push_back(curLevel);
}
return res;
}
vector<int> inorderTraversal(TreeNode* root) {
vector<int> result;
stack<TreeNode*> st;
while (!st.empty() || root) {
if (root) {
st.push(root);
root = root->left;
} else {
root = st.top();
st.pop();
result.push_back(root->val);
root = root->right;
}
}
return result;
}
vector<int> inorderTraversal1(TreeNode* root) {
vector<int> result;
core(root, result);
return result;
}
void core(TreeNode* root, vector<int>& result) {
if (root == nullptr)
return;
core(root->left, result);
result.push_back(root->val);
core(root->right, result);
}
};
// @lc code=end