-
Notifications
You must be signed in to change notification settings - Fork 7
/
PrintTreesInLines.cpp
54 lines (52 loc) · 1.41 KB
/
PrintTreesInLines.cpp
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
// C++ Solution 1:
class Solution {
public:
vector<vector<int> > Print(TreeNode* root) {
vector<vector<int>> res;
if (root==NULL)
return res;
queue<TreeNode*> q;
q.push(root);
while(!q.empty())
{
int count = q.size();
vector<int> out;
while(count>0)
{
TreeNode* node = q.front();
q.pop();
out.push_back(node->val);
if (node->left)
q.push(node->left);
if (node->right)
q.push(node->right);
count--;
}
res.push_back(out);
}
return res;
}
};
// C++ Solution 2:
class Solution {
public:
vector<vector<int>> Print(TreeNode* root) {
vector<vector<int>> res;
if (root==NULL)
return res;
helper(root, res,0);
return res;
}
void helper(TreeNode* root, vector<vector<int>> &res, int level)
{
if (root==NULL)
return;
if (res.size()==level)
res.push_back(vector<int>());
res[level].push_back(root->val);
if (root->left)
helper(root->left,res,level+1);
if (root->right)
helper(root->right,res,level+1);
}
};