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]
.
Credits:
Special thanks to @amrsaqr for adding this problem and creating all test cases.
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) { Alist<integer> ans =NewArraylist<integer>(); -Addright (ans,0, root); - returnans; the } - - Public voidAddright (list<integer> ans,intHigh , TreeNode root) { - if(Root = =NULL)return; + if(ans.size () = =High ) Ans.add (root.val);//Add a single element to each layer -Addright (ans,high+1, root.right); +Addright (ans,high+1, root.left); A } at}
The problem can be solved by recursion, each time the element is added from the far right, and each layer joins one. Left dial hand tree can join the situation is higher than the right sub-tree.
Such as:
1
/ \
2 5
/
4
In the case where element 4 is located. Although the code is recursive, the actual program execution time is O (n) complexity.
Solution 2:
The problem can also be used in sequence traversal, each layer of the value of the right node is added to the list.
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) { Alist<integer> ans =NewArraylist<integer>(); - if(Root = =NULL)returnans; -deque<treenode> q =NewLinkedlist<treenode>(); the intCurrent = 1,next = 0;//Use current and next to mark the number of elements in the next layer - TreeNode node; - q.addlast (root); - while(Q.size () > 0){ +node =Q.removefirst (); -current--; + if(Node.left! =NULL){ A Q.addlast (node.left); atnext++; - } - if(Node.right! =NULL){ - Q.addlast (node.right); -next++; - } in if(current = = 0){ - Ans.add (node.val);//Add the right element of the layer each time toCurrent =Next; +Next = 0; - } the } * returnans; $ }Panax Notoginseng -}
Actual run time:
Better solution one.
199. Binary Tree Right Side View Java solutions