Topic
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].
Ideas
Hierarchical traversal
Code
/*-------------------------------------------------------------------* Date: 2014-04-05 * SJF0115 * Title: 1 99.Binary Tree Right Side View * Source: https://leetcode.com/problems/binary-tree-right-side-view/* Result: AC * source : Leetcode * Summary:--------------------------------------------------------------------*/ #include <iostream> #include <vector> #include <queue> using namespace STD;structtreenode{intVal TreeNode *left; TreeNode *right; TreeNode (intx): Val (x), left (null), right (null) {}};classSolution { Public: vector<int>Rightsideview (TreeNode *root) { vector<int>Resultif(Root = =nullptr){returnResult }//if queue<TreeNode*>Cur queue<TreeNode*>Next Cur.push (root); Result.push_back (Root->val); TreeNode *node,*pre;//Hierarchical Traversal while(!cur.empty ()) {pre =nullptr; while(!cur.empty ()) {node = Cur.front (); Cur.pop ();if(Node->left) {Next.push (node->left); Pre = node->left; }//if if(Node->right) {Next.push (node->right); Pre = node->right; }//if}//while if(Pre! =nullptr) {Result.push_back (pre->val); }//ifSwap (Cur,next); }//while returnResult } };intMain () {solution solution; TreeNode *root =NewTreeNode (1); Root->left =NewTreeNode (2); Root->right =NewTreeNode (3); Root->left->right =NewTreeNode (5); Root->right->right =NewTreeNode (4); vector<int>result = Solution.rightsideview (root); for(inti =0; i < result.size (); ++i) {cout<<result[i]<<" "; }//for cout<<endl;return 0;}
Run time
[Leetcode]199.binary Tree Right Side View