199. 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]
.
其实就是层序遍历 的每层的最后一个元素!!!!
# 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 import queue class Solution: def rightSideView(self, root: Optional[TreeNode]) -> List[int]: q = queue.Queue() res = [] if root == None: return [] q.put(root) while q.qsize(): sz = q.qsize() for i in range(sz): top = q.get() if i == sz -1: res.append(top.val) if top.left : q.put(top.left) if top.right : q.put(top.right) return res
class Solution { public: vector<int> rightSideView(TreeNode* root) { vector<int> res ; if(root == nullptr) return res; queue<TreeNode*> q; q.push(root); while(!q.empty()) { int cnt = q.size(); for(int i = 0 ; i < cnt ; ++i) { auto node = q.front();q.pop(); if(i == cnt -1) res.push_back(node->val); if(node->left != nullptr) q.push(node->left); if(node->right!= nullptr) q.push(node->right); } } return res; } };
1 class Solution { 2 3 public List<Integer> rightSideView(TreeNode root) { 4 List<Integer> res = new ArrayList<Integer>(); 5 Queue<TreeNode> queue = new LinkedList<TreeNode>(); 6 if(root==null) return res; 7 queue.offer(root); 8 int level_num = 1; 9 while (!queue.isEmpty()) { 10 level_num = queue.size(); 11 for(int i = 0; i < level_num; i++){ 12 TreeNode node = queue.poll(); 13 if(i==level_num-1) 14 res.add(node.val); 15 if(node.left != null) queue.offer(node.left); 16 if(node.right != null) queue.offer(node.right); 17 18 } 19 } 20 return res; 21 } 22 }