A simple application of level-order traversal. Just push the last node of each level into the result.
The code is as follows.
1 classSolution {2 Public:3vector<int> Rightsideview (treenode*root) {4vector<int>Right ;5 if(!root)returnRight ;6Queue<treenode*>tovisit;7 Tovisit.push (root);8 while(!Tovisit.empty ()) {9treenode* Rightnode =Tovisit.back ();TenRight.push_back (Rightnode,val); One intnum =tovisit.size (); A for(inti =0; i < num; i++) { -treenode* node =Tovisit.front (); - Tovisit.pop (); the if(node-to-left) Tovisit.push (node-Left ); - if(node-right) Tovisit.push (node-Right ); - } - } + returnRight ; - } +};
Well, the above code is of BFS. This problem can still is solved using DFS. The code is as follows. Play with it-see how it works:-)
1 classSolution {2 Public:3vector<int> Rightsideview (treenode*root) {4vector<int>Right ;5 if(!root)returnRight ;6Rightview (Root, right,0);7 }8 Private:9 voidRightview (treenode* node, vector<int>& Right,intLevel ) {Ten if(!node)return; One if(Level = =right.size ()) ARight.push_back (Node-val); -Rightview (node-right, right, level +1); -Rightview (node-I, right, level +1); the } -};
[Leetcode] Binary Tree Right Side View