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.
For example:
Given the following binary tree,
1 <--- / \ 2 3 <--- \ \ 5 4 <---
You should return [1, 3, 4]
.
基本思路:
1.广度优先搜索
广度优先搜索,在访问每层最后(最右)一个结点时,将其存入结果集中。
在leetcode上实际运行时间为8ms。
/**
* 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)
return ans;
queue<TreeNode *> q;
q.push(root);
while (!q.empty()) {
int count = q.size();
while (count--) {
root = q.front();
q.pop();
if (!count)
ans.push_back(root->val);
if (root->left)
q.push(root->left);
if (root->right)
q.push(root->right);
}
}
return ans;
}
};
2. 深度优先搜索
对树做 中 右 左的 递归访问。
并在首次进入下一层次结点时,将该结点值存入结果集中。
在leetcode上实际执行时间为4ms。
class Solution {
public:
vector<int> rightSideView(TreeNode* root) {
vector<int> ans;
dfs(root, 0, ans);
return ans;
}
void dfs(TreeNode *root, int level, vector<int> &ans) {
if (!root) return;
if (level == ans.size())
ans.push_back(root->val);
dfs(root->right, level+1, ans);
dfs(root->left, level+1, ans);
}
};
深度优先搜索在执行时间要好于广度优先搜索,大约是因为队列的出、入操作都是相对耗时的操作。毕竟深度优先搜索的在运行时,栈的扩张和收缩是个非常轻量级的操作。