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 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.
Hierarchy traversal, to the last node of each layer, the RET is loaded
The last node of each layer is judged by:
(1) Queue is empty
(2) Next node to traverse Next level
/** Definition for binary tree * struct TreeNode {* int val; * TreeNode *left; * TreeNode *right; * T Reenode (int x): Val (x), left (null), right (NULL) {} *}; */structnode{TreeNode*tnode; intLevel ; Node (TreeNode* t,intl): Tnode (t), level (L) {}};classSolution { Public: Vector<int> Rightsideview (TreeNode *root) {Vector<int>ret; if(Root = =NULL)returnret; Queue<Node*>Q; intCurlevel =0; Node* RootNode =NewNode (Root,0); Q.push (RootNode); while(!Q.empty ()) {Node* Front =Q.front (); Q.pop (); if(Q.empty () | | q.front ()->level > Front->Level )//Last node of the current levelRet.push_back (front->tnode->val); if(front->tnode->Left ) {Node* Leftnode =NewNode (Front->tnode->left, front->level+1); Q.push (Leftnode); } if(front->tnode->Right ) {Node* Rightnode =NewNode (Front->tnode->right, front->level+1); Q.push (Rightnode); } } returnret; }};
"Leetcode" 199. Binary Tree Right Side View