给定一棵二叉树,想象自己站在它的右侧,按照从顶部到底部的顺序,返回从右侧所能看到的节点值。
示例:
输入: [1,2,3,null,5,null,4]
输出: [1, 3, 4]
解释:
1 <---
/ \
2 3 <---
\ \
5 4 <---
这个题一开始想的很简单,想着只要一直找右节点就可以了,忘了只有左节点的情况了,所以还是乖乖的用层次遍历,然后输出每层最后一个。
C++源代码:
/**
* 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> res;
if(!root) return res;
queue<TreeNode*> q;
q.push(root);
while(!q.empty()){
res.push_back(q.back()->val);
int n = q.size();
for(int i=0;i<n;i++){
TreeNode *node = q.front();
q.pop();
if(node->left) q.push(node->left);
if(node->right) q.push(node->right);
}
}
return res;
}
};
python3源代码:
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def rightSideView(self, root: TreeNode) -> List[int]:
res = []
if root==None:
return res
q = [root]
while len(q)!=0:
res.append(q[-1].val)
n = len(q)
for i in range(n):
node = q.pop(0)
if node.left:
q.append(node.left)
if node.right:
q.append(node.right)
return res