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] .
1 PublicList<integer>Rightsideview (TreeNode root) {2list<integer> res =NewArraylist<integer> ();//Save the result to this variable3 if(Root = =NULL)returnRes;4 5linkedlist<treenode> queue =NewLinkedlist<treenode>(); 6 Queue.add (root); 7 intcurlevcnt = 1; 8 intnextlevcnt = 0; 9 intLevelres = 0; Ten One while(!Queue.isempty ()) { ATreeNode cur =Queue.poll (); -curlevcnt--; - //Levelres.add (Cur.val); the - if(Cur.left! =NULL){ - Queue.add (Cur.left); -nextlevcnt++; + } - if(Cur.right! =NULL){ + Queue.add (cur.right); Anextlevcnt++; at } - - if(curlevcnt = = 0){ -curlevcnt =nextlevcnt; -nextlevcnt = 0; -Levelres =Cur.val; in Res.add (Cur.val); - //levelres =new int; to } + } - returnRes; the *}
Very similar with Binary Tree level Order Traverse
Http://www.cnblogs.com/hygeia/p/4704027.html
Binary Tree Right Side View