Simple Java solution using a HashMap


  • 0
    T
     * Definition for binary tree with next pointer.
     * public class TreeLinkNode {
     *     int val;
     *     TreeLinkNode left, right, next;
     *     TreeLinkNode(int x) { val = x; }
     * }
     */
    public class Solution {
        public void connect(TreeLinkNode root) {
            
            HashMap<Integer, ArrayList<TreeLinkNode>> map = new HashMap<Integer, ArrayList<TreeLinkNode>>();
            connect(root, map, 0);
        }
        
        public void connect(TreeLinkNode n, HashMap<Integer, ArrayList<TreeLinkNode>> map, int level){
            
            if(n == null){
                return;
            }
            
            ArrayList<TreeLinkNode> list = null;
            if(!map.containsKey(level)){
                list = new ArrayList<>();
                n.next = null;
                list.add(n);
            } else {
                list = map.get(level);
                TreeLinkNode c = list.get(list.size()-1);
                c.next = n;
                list.add(n);
            }
            
            map.put(level, list);
            
            connect(n.left, map, level + 1);
            connect(n.right, map, level + 1);
            
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.