题目链接:二叉树的右视图
给定一个二叉树的 根节点 root,想象自己站在它的右侧,按照从顶部到底部的顺序,返回从右侧所能看到的节点值。
方法一:层序遍历
/**
* 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<int> rightSideView(TreeNode* root) {
vector<int> ans;
if (root == nullptr) return ans;
queue<TreeNode*> q;
q.push(root);
int num = 0;
while (q.size()) {
int t = q.size();
//int num;
while (t--) {
TreeNode* tmp = q.front();
q.pop();
num = tmp->val;
if (tmp->left != nullptr) q.push(tmp->left);
if (tmp->right != nullptr) q.push(tmp->right);
}
ans.push_back(num);
}
return ans;
}
};
方法二:bfs
/**
* 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<int> rightSideView(TreeNode* root) {
vector<int> ans;
if (!root) return ans;
queue<TreeNode*> q;
q.push(root);
while (q.size()) {
int size = q.size();
ans.push_back(q.front()->val);
for (int i = 0;i < size;i++) {
TreeNode* node = q.front();
q.pop();
if (node->right) q.push(node->right);
if (node->left) q.push(node->left);
}
}
return ans;
}
};
方法三:dfs
/**
* 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:
void dfs(TreeNode* root,int depth,vector<int>& ans) {
if (root == nullptr) return ;
if (depth == ans.size()) ans.push_back(root->val);
dfs(root->right,depth+1,ans);
dfs(root->left,depth+1,ans);
}
vector<int> rightSideView(TreeNode* root) {
vector<int> ans;
dfs(root,0,ans);
return ans;
}
};