Original question:
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]
.
Test instructions: Look at the binary tree from the right, see the rightmost node of each layer, the node can be on the right subtree, can be on the left sub-tree.
Problem-solving ideas: sequence traversal, in each layer from right to left to access the node, so in each drop layer will be the first access to the right node, this node is the nodes we want, we use markedlevel to represent the largest layer has been identified, that is, the most right node has been selected, with currentlevel indicates the layer on which the node is being accessed, so that when the first currentlevel> markedlevel , we are accessing the right-most node. Using recursive algorithm, the idea is clear, the code quantity is small. The Java implementation is as follows:
public class solution {arraylist<integer> list = new arraylist<integer> (); int markedlevel = 0;public void leve Ldown (TreeNode root,int currentlevel) {if (root = null) {return;} if (currentlevel>markedlevel) {//First currentlevel greater than markedlevel means access to the right-most node list.add (root.val); markedlevel = currentlevel;//no longer records the current layer}leveldown (root.right,currentlevel+1); Always first accesses the right-most node of each layer Leveldown (root.left,currentlevel+1);} Public list<integer> Rightsideview (TreeNode root) { leveldown (root,1); return list; }}
WORKAROUND: If you need to output the leftmost view of a two-fork tree, you only need to access the left node each time first.
Reference Address: http://www.geeksforgeeks.org/print-right-view-binary-tree-2/
Leetcode:binary Tree Right Side View