Given a binary tree, imagine yourself standing on the

*right*side of it, return the values of the nodes you can see ordered from top to bottom.
For example:

Given the following binary tree,

Given the following binary tree,

1 <--- / \ 2 3 <--- \ \ 5 4 <---

You should return

`[1, 3, 4]`

.**Idea:**

Obviously, the question asks for a BFS. The major difference from the traditional BFS is it only prints the right-most nodes for each level. Consequently, the basic idea is to add right child before adding the left child. For each level, only print out the first node, which must be the right-most node.

**Code (Java):**

/** * 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) { List<Integer> result = new ArrayList<Integer>(); if (root == null) { return result; } Queue<TreeNode> queue = new LinkedList<TreeNode>(); queue.offer(root); while (!queue.isEmpty()) { int size = queue.size(); for (int i = 0; i < size; i++) { TreeNode curr = queue.poll(); if (i == 0) { result.add(curr.val); } if (curr.right != null) { queue.offer(curr.right); } if (curr.left != null) { queue.offer(curr.left); } } } return result; } }

**A DFS solution:**

/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class Solution { public List<Integer> rightSideView(TreeNode root) { List<Integer> result = new ArrayList<Integer>(); if (root == null) { return result; } rightSideViewHelper(root, 0, result); return result; } private void rightSideViewHelper(TreeNode root, int level, List<Integer> result) { if (root == null) { return; } if (level == result.size()) { result.add(root.val); } rightSideViewHelper(root.right, level + 1, result); rightSideViewHelper(root.left, level + 1, result); } }

## No comments:

## Post a Comment