https://leetcode.com/problems/binary-tree-right-side-view/
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] .
Problem Solving Ideas:
This problem is relatively simple, hierarchical traversal, each layer output the last node can be.
/*** Definition for Binary tree * public class TreeNode {* Int. val; * TreeNode left; * TreeNode right; * TreeNode (int x) {val = x;} }*/ Public classSolution { PublicList<integer>Rightsideview (TreeNode root) {List<Integer> result =NewArraylist<integer>(); if(Root = =NULL) { returnresult; } Queue<TreeNode> queue =NewLinkedlist<treenode>(); Queue.offer (root); while(Queue.size () > 0) { intSize =queue.size (); while(Size > 0) {TreeNode current=Queue.poll (); if(Current.left! =NULL) {queue.offer (current.left); } if(Current.right! =NULL) {queue.offer (current.right); } if(Size = = 1) {result.add (current.val); } size--; } } returnresult; }}
Binary Tree Right Side View