/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode() {} * TreeNode(int val) { this.val = val; } * TreeNode(int val, TreeNode left, TreeNode right) { * this.val = val; * this.left = left; * this.right = right; * } * } */ class Solution { public List<Integer> rightSideView(TreeNode root) { List<Integer> rightVisibleList = new ArrayList<> (); if (root == null) return rightVisibleList; Queue<TreeNode> q = new LinkedList<>(); q.add(root); while (!q.isEmpty()) { int size = q.size(); for (int i=0; i<size; i++) { TreeNode out = q.poll(); if (i == size-1) rightVisibleList.add(out.val); if (out.left != null) q.add(out.left); if (out.right != null) q.add(out.right); } } return rightVisibleList; } }
In case we were to solve it for Left Side View we would have just kept a track of the first element at each level and that would have done the deal!
Happy Coding until next time!
No comments:
Post a Comment