LeetCode 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]
.
Credits:
Special thanks to @amrsaqr for adding this problem and creating all test cases.
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> res; 14 if (root == NULL) { 15 return res; 16 } 17 queue<TreeNode*> que; 18 que.push(root); 19 while (!que.empty()) { 20 int len = que.size(); 21 res.push_back(que.back()->val); 22 for (int i=0; i<len; i++) { 23 TreeNode* node = que.front(); 24 que.pop(); 25 if (node->left != NULL) { 26 que.push(node->left); 27 } 28 if (node->right != NULL) { 29 que.push(node->right); 30 } 31 } 32 } 33 return res; 34 } 35 };
会不会有更简单的方法呢