LEETCODE算法:199. Binary Tree Right Side View

题目

Given a binary tree, imagine yourself standing on the right side of it, return the values of the nodes you can see ordered from top to bottom.

Example:

Input: [1,2,3,null,5,null,4] Output: [1, 3, 4] Explanation:

1 <--- /
2 3 <---  
5 4 <---

题解

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
/**
* 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<int> rightSideView(TreeNode* root) {
vector<int> ans;
if(root==NULL) return ans;
queue<pair<TreeNode*,int>> q;
q.push({root,0});
int pre=root->val,prei=0;
while(!q.empty())
{
auto [tmp,i]=q.front();//指针,当前层数
if(i>prei)
{
ans.push_back(pre);
prei=i;
}
pre=tmp->val;
q.pop();
if(tmp->left!=NULL) q.push({tmp->left,i+1});
if(tmp->right!=NULL) q.push({tmp->right,i+1});
}
ans.push_back(pre);
return ans;
}
};
  • 也可以深度优先搜索,先有右后左每层第一个为右视图,先左后右每层最后一个是右视图元素