Easy understand and precise Java code

  • 6

    Use dummy node to avoid unneccesary if sentense:

     public void connect(TreeLinkNode root) {
            while(root != null){
                TreeLinkNode firstNode = new TreeLinkNode(0); //Dummy head
                TreeLinkNode pre = firstNode;
                for(TreeLinkNode cur = root; cur != null; cur = cur.next){
                    if(cur.left != null){
                        pre.next = cur.left;
                        pre = cur.left;
                    if(cur.right != null){
                        pre.next = cur.right;
                        pre = cur.right;
                root = firstNode.next;

  • 0

    Thank you for your solution. Could you explain more? I hava some doubt about how the firstNode point to the first node on next depth of this tree

  • 1

    Sure. firstNode is the dummy head of the next level, so firstNode.next will be the actual first node of next level. We use pre to record the previous node in next level and pre is initialized to firstNode.

Log in to reply

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