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] .
The code is as follows:
1 /**2 * Definition for a binary tree node.3 * 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) { A Booleanflag=true; -List<integer> list=NewArraylist<>(); -Arraylist<treenode> res=NewArraylist<treenode>(); theMap<integer,integer> map=NewHashmap<>(); - - if(root==NULL) - returnlist; + -res=Leveltraverse (root); + List.add (root.val); AMap.put (0,0); at - while(flag) - { - while(root.right!=NULL) - { -root=Root.right; in List.add (root.val); - Map.put (Res.indexof (Root), res.indexof (root)); to + } - if(root.left!=NULL) the { *root=Root.left; $ List.add (root.val);Panax Notoginseng Map.put (Res.indexof (Root), res.indexof (root)); - } the Else{ + if(Res.indexof (Root) -1<0) Aflag=false; the Else { +Root=res.get (Res.indexof (root)-1); - if(Map.containskey (Res.indexof (Root ))) $ Break; $ } - } - } the returnlist; - }Wuyi the PublicArraylist<treenode> leveltraverse (TreeNode root)//horizontal traversal of the tree - { WuArraylist<treenode> list=NewArraylist<treenode>(); -queue<treenode> queue =NewLinkedlist<treenode>(); About Queue.add (root); $ while(Queue.size () >0) - { -TreeNode a=(TreeNode) Queue.peek (); - Queue.remove (); A List.add (a); + if(a.left!=NULL) the Queue.add (a.left); - if(a.right!=NULL) $ Queue.add (a.right); the } the the returnlist; the } -}
199. Binary Tree Right Side View