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