题目
给定一个二叉树的 根节点 root,想象自己站在它的右侧,按照从顶部到底部的顺序,返回从右侧所能看到的节点值。
示例 1:
输入: [1,2,3,null,5,null,4] 输出: [1,3,4]
示例 2:
输入: [1,null,3] 输出: [1,3]
示例 3:
输入: [] 输出: []
解题
方法一:BFS
python解法
# Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def rightSideView(self, root: TreeNode) -> List[int]: if not root: return [] queue = [root] res = [] while queue: l = len(queue) for i in range(l): cur = queue.pop(0) if i==l-1: # 在层序遍历基础上新加的 res.append(cur.val) left,right = cur.left,cur.right if left: queue.append(left) if right: queue.append(right) return res
c++解法
class Solution { public: vector<int> rightSideView(TreeNode* root) { if(!root) return {}; vector<int> res; queue<TreeNode*> queue; queue.push(root); while(!queue.empty()){ int l=queue.size(); while(l--){ TreeNode* cur=queue.front(); queue.pop(); if(l==0){ res.push_back(cur->val); } if(cur->left){ queue.push(cur->left); } if(cur->right){ queue.push(cur->right); } } } return res; } };