return The values of the nodes can see ordered from top to bottom. For Example:given The following binary tree, 1 <---/ 2 3 <--- \ 5 4 <---return [1, 3, 4].
This problem is BT level Order traversal, each time you want to change a layer, record the current node
1 /**2 * Definition for binary tree3 * public class TreeNode {4 * int val;5 * TreeNode left;6 * TreeNode right;7 * TreeNode (int x) {val = x;}8 * }9 */Ten Public classSolution { One PublicList<integer>Rightsideview (TreeNode root) { Aarraylist<integer> res =NewArraylist<integer>(); - if(Root = =NULL)returnRes; -linkedlist<treenode> queue =NewLinkedlist<treenode>(); the Queue.offer (root); - intPnum = 1; - intCNum = 0; - while(!Queue.isempty ()) { +TreeNode cur =Queue.poll (); -pnum--; + if(Cur.left! =NULL) { A Queue.offer (cur.left); atcnum++; - } - if(Cur.right! =NULL) { - Queue.offer (cur.right); -cnum++; - } in if(Pnum = = 0) { - Res.add (cur.val); toPnum =CNum; +CNum = 0; - } the } * returnRes; $ }Panax Notoginseng}
Leetcode:binary Tree Right Side View