-
Notifications
You must be signed in to change notification settings - Fork 0
/
199. 二叉树的右视图.cc
60 lines (56 loc) · 1.4 KB
/
199. 二叉树的右视图.cc
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
/* 错误示例:[1,2,3,4],预期结果应该为[1,3,4] */
/* 不能仅仅遍历右子树 */
class Solution {
public:
vector<int> rightSideView(TreeNode* root)
{
vector<int> res;
if(root == nullptr) return res;
dfs(root, res);
return res;
}
//preorder
/* 优先遍历右子树,当右子树不存在时,遍历左子树 */
void dfs(TreeNode *root, vector<int> &res)
{
if(root->left == nullptr && root->right == nullptr)
{
res.push_back(root->val);
return ;
}
res.push_back(root->val);
if(root->right)
{
dfs(root->right, res);
}
else if(root->left)
{
dfs(root->left, res);
}
}
};
/* bfs,取每层遍历的最右边元素 */
/* 4ms */
class Solution {
public:
vector<int> rightSideView(TreeNode* root)
{
vector<int> res;
if(root == nullptr) return res;
queue<TreeNode *> que;
que.push(root);
int size;
while((size = que.size()) != 0)
{
TreeNode *node;
for(int i=0; i<size; ++i)
{
node = que.front(); que.pop();
if(node->left) que.push(node->left);
if(node->right) que.push(node->right);
}
res.push_back(node->val);
}
return res;
}
};