- 二叉树的右视图
给定一棵二叉树,想象自己站在它的右侧,按照从顶部到底部的顺序,返回从右侧所能看到的节点值。
示例:
输入: [1,2,3,null,5,null,4]
输出: [1, 3, 4]
解释:
1 <—
/
2 3 <—
\
5 4 <—
思路,bfs就是每层最后一个结点
dfs 前序遍历,不过是根右左,每层访问的第一个数,添加进去
class Solution {
public:
vector<int> res;
int H;
vector<int> rightSideView(TreeNode* root) {
if (root == NULL)return res;
//levelTra(root);
preorder(root,0);
return res;
}
void levelTra(TreeNode* root) //层次遍历,每层最后一个元素
{
queue<TreeNode*> q;
q.push(root);
while (!q.empty()){
int current_size = q.size();
for (int i = 0; i < current_size; i++)
{
root = q.front(); q.pop();
if (i == current_size - 1){
//如果是最后一个数据,就添加到结果中
res.push_back(root->val);
}
if (root->left){
q.push(root->left);
}
if (root->right){
q.push(root->right);
}
}
}
}
void preorder(TreeNode* root,int now) //根右左
{
if (root == NULL) return;
if (now == H){
//如果当前深度还没有被访问过
res.push_back(root->val);
H++;
}
preorder(root->right, now + 1);
preorder(root->left, now + 1);
}
};