A Simple Java Code with Explanation


  • 0
    R

    remember all nodes default next is null, so the right most line in the tree need not to be considered, once the helper return to main function, we are done.

    public class Solution {
    
        HashMap map = new HashMap<Integer, TreeLinkNode>();// <level index, tree node need to be assign a next>
        public void connect(TreeLinkNode root) {
        helper(root, 0); 
    }
    
      private void helper(TreeLinkNode root, int level){
        if (root == null) return;
        if (!map.containsKey(level))// first time visit this level
            map.put(level, root);
        else{ // this level has a node need a next 
            TreeLinkNode n = (TreeLinkNode)map.get(level);
            n.next = root; // assign current root (at this level) to n.next
            map.put(level, root); // replace n with root (root need a next too)
        }
        helper(root.left, level+1);
        helper(root.right, level+1);
    }
    

    }


Log in to reply
 

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