Leetcode:binary Tree Right Side View

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.