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] .
Credits:
Special thanks to @amrsaqr for adding this problem and creating all test cases.
Wide search, from the right to the left plus, layered, the first node in the queue to take the Val to join the list
/** * Definition for Binary tree * public class TreeNode {* int val, * TreeNode left, * TreeNode right; *
treenode (int x) {val = x;} *} */public class Solution {public list<integer> Rightsideview (TreeNode root) { C5/>return BFS (root); } Private list<integer> BFS (TreeNode root) { if (root==null) return new arraylist<integer> (); Queue<treenode> cur = new linkedlist<> (); Queue<treenode> next = new linkedlist<> (); Cur.offer (root); list<integer> res = new arraylist<> (); while (!cur.isempty ()) { Res.add (Cur.peek (). val); while (!cur.isempty ()) { TreeNode t = cur.poll (); if (t.right!=null) Next.offer (t.right); if (t.left!=null) Next.offer (t.left); } queue<treenode> tmp = cur; cur = next; Next = tmp; } return res; }}
[Leetcode] Binary Tree Right Side View