# 199.Binary-Tree-Right-Side-View

## ้ข็ฎๅฐๅ

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 see ordered from top to bottom.

Example:

Input: [1,2,3,null,5,null,4]
Output: [1, 3, 4]
Explanation:

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

## ไปฃ็ 

### Approach #1 Two Stacks + DFS

``````/**
* Definition for a binary tree node.
* public class TreeNode {
*     int val;
*     TreeNode left;
*     TreeNode right;
*     TreeNode(int x) { val = x; }
* }
*/
class Solution {
public List<Integer> rightSideView(TreeNode root) {
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
int max_depth = -1;

Stack<TreeNode> nodeStack = new Stack<TreeNode>();
Stack<Integer> depthStack = new Stack<Integer>();
nodeStack.push(root);
depthStack.push(0);

while (!nodeStack.isEmpty()) {
TreeNode node = nodeStack.pop();
int depth = depthStack.pop();

if (node != null) {
max_depth = Math.max(max_depth, depth);

if (!map.containsKey(depth)) {
map.put(depth, node.val);
}

nodeStack.push(node.left);
nodeStack.push(node.right); // ๅๅผนๅบๅณ่็น
depthStack.push(depth + 1);
depthStack.push(depth + 1);
}
}

List<Integer> rightView = new ArrayList<Integer>();
for (int depth = 0; depth <= max_depth; depth++) {
}

return rightView;
}
}``````

### Approach #2 Two Queues + BFS

``````class Solution {
public List<Integer> rightSideView(TreeNode root) {
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
int max_depth = -1;

Queue<TreeNode> nodeQueue = new LinkedList<TreeNode>();
Queue<Integer> depthQueue = new LinkedList<Integer>();

while (!nodeQueue.isEmpty()) {
TreeNode node = nodeQueue.remove();
int depth = depthQueue.remove();

if (node != null) {
max_depth = Math.max(max_depth, depth);

map.put(depth, node.val);