Topic:
Given A binary tree, imagine yourself standing on the right side of it, return the values of the nodes you can SE E 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.
Code:
/** Definition for a binary tree node. * struct TreeNode {* int val; * TreeNode *left; * TreeNode *right ; * TreeNode (int x): Val (x), left (null), right (NULL) {} *}; */classSolution { Public: Vector<int> Rightsideview (treenode*root) {Vector<int>ret; Queue<TreeNode*>Curr; Queue<TreeNode*>Next; if(Root) {Curr.push (root); Ret.push_back (root->val); } while( !Curr.empty ()) { while( !Curr.empty ()) {TreeNode* TMP =Curr.front (); Curr.pop (); if(tmp->left) Next.push (tmp->Left ); if(tmp->right) Next.push (tmp->Right ); } if(!next.empty ()) Ret.push_back (Next.back ()val); Swap (NEXT,CURR); } returnret; }};
Tips
BFS algorithm, level order traversal binary tree
The value of the right-most element of each level is retained each time.
"Binary Tree right Side View" cpp