[Leetcode] Binary Tree Right Side View

Source: Internet
Author: User

Original title Link: https://leetcode.com/problems/binary-tree-right-side-view/

Test Instructions Description:

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] .

Exercises

This problem is very interesting, is to find two fork tree from the right side to see the number of times, in fact, the idea is very simple, that is, return to the right of each layer of a number on the right, in the binary tree sequence traversal of the code slightly modified can be. The sequence traversal of the two-tree is not clear to the friend, can see my previous blog "Two fork Tree complete summary." Specifically, there is nothing to say, directly on the code:

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) { Alist<integer> res =NewArraylist<integer>(); -         if(root==NULL) -             returnRes; theQueue<treenode> Q =NewLinkedlist<treenode>();  - Q.offer (root); -         intCurlevel = 1; - Res.add (root.val); +          while(!Q.isempty ()) { -             intLevelsize =q.size (); +             intCount = 0; ATreeNode last =NULL; at              while(count<levelsize) { -TreeNode p =Q.poll (); -                 if(p.left!=NULL){ -Last =P.left; - Q.offer (p.left); -                 } in                 if(p.right!=NULL){ -Last =P.right; to Q.offer (p.right); +                 } -count++; the             } *             if(last!=NULL) $ Res.add (last.val);Panax Notoginseng              -         } the         returnRes; +     } A}

[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.