Saturday, 12 November 2016

Binary Tree Right Side View LeetCode Java

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,
   1            <---
 /   \
2     3         <---
 \     \
  5     4       <---
You should return [1, 3, 4].



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> res = new ArrayList<Integer>();
        HashMap<Integer,List<Integer>> map = new HashMap<Integer, List<Integer>>();
    traverse(root,map, 0);
 
    for(int i = 0 ; i < map.size() ; i++){
        List<Integer> temp = map.get(i);
        if(temp != null){
            res.add(temp.get(temp.size() -1));
        }
    }
    return res;
     
    }
 
    private void traverse(TreeNode root, HashMap<Integer,List<Integer>> map, int level ){
 
    if(root != null){
     
        if(map.containsKey(level)){
            List<Integer> temp = map.get(level);
            temp.add(root.val);
            map.put(level,temp);
        }
        else{
            List<Integer> temp = new ArrayList<Integer>();
            temp.add(root.val);
            map.put(level,temp);
        }
        level++;
        traverse(root.left,map,level);
        traverse(root.right,map,level);
     
    }
    }
}

No comments:

Post a Comment