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.
For example:
Given the following binary tree,
1 <--- / \ 2 3 <--- \ \ 5 4 <---
You should return [1, 3, 4]
.
分析:
这题比较有意思,从右边查看二叉树。
这题可以采用层次遍历的方式,每次获取当前层最后遍历的元素保存起来。
我这里用的是编程之美里提到的双指针法,大概的思路是:使用list存储所有遍历到的元素,前指针每次记录当前层开始位置的元素的位置,后指针每次记录当前层最后一个元素的位置,使用另一个list存储后指针每次位置的元素的值,即为所要的结果。遍历时,前指针依次遍历它所指的位置的元素直到到达后指针所指向的元素,同时将遍历时经过的元素添加到list中。
代码:
class Solution(object):
def rightSideView(self, root):
"""
:type root: TreeNode
:rtype: List[int]
"""
res = []
vis = []
p = root
if p:
vis.append(p)
front, end = 0, 1
else:
return res
while front < end:
res.append(vis[-1].val)
while front < end:
cur = vis[front]
if cur.left:
vis.append(cur.left)
if cur.right:
vis.append(cur.right)
front += 1
end = len(vis)
return res
从Discuss中看到的代码:
vector<int> rightSideView(TreeNode* root) {
vector<int> V;
queue<TreeNode*> Q;
if (root!=NULL) Q.push(root);
while (!Q.empty()) {
int k = Q.size();
for (int i=0; i<k; i++) {
TreeNode* rt = Q.front();
if (i==0) V.push_back(rt->val);
if (rt->right)Q.push(rt->right);
if (rt->left) Q.push(rt->left);
Q.pop();
}
}
return V;
}