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]
.
解题思路:
这题和上一题Binary Tree Zigzag Level Order Traversal很相似,都需要按层遍历二叉树;
不同的是,由于Binary Tree Zigzag Level Order Traversal需要Z型遍历,需要用到“先入后出”的方法,因此用栈stack来实现;
而本题,需要每层由右向左遍历,因此用到“先进先出”,所以使用queue来实现较为方便;
需要两个queue,一个保存当前层的结点,另一个保存下一层的结点;
每层结点queue中第一个值,就是最右端值,输出这个值。
代码:
1 /** 2 * Definition for a binary tree node. 3 * struct TreeNode { 4 * int val; 5 * TreeNode *left; 6 * TreeNode *right; 7 * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 * }; 9 */ 10 class Solution { 11 public: 12 vector<int> rightSideView(TreeNode* root) { 13 vector<int> ret; 14 queue<TreeNode*> cur_layer; 15 cur_layer.push(root); 16 queue<TreeNode*> next_layer; 17 if (!root) 18 return ret; 19 20 while (!cur_layer.empty()) { 21 ret.push_back(cur_layer.front()->val); 22 while (!cur_layer.empty()) { 23 TreeNode* node = cur_layer.front(); 24 cur_layer.pop(); 25 if (node->right) 26 next_layer.push(node->right); 27 if (node->left) 28 next_layer.push(node->left); 29 } 30 swap(cur_layer, next_layer); 31 } 32 33 return ret; 34 } 35 };