2ms Clear Java Solution Using A Dummy Node


  • 0
    S
    public void connect(TreeLinkNode root) {
        if (root == null){
            return;
        }
        
        while (root != null){
            //find leftMost
            TreeLinkNode leftMost = null;
            while (root != null){
                if (root.left != null){
                    leftMost = root.left;
                    break;
                } else if (root.right != null){
                    leftMost = root.right;
                    break;
                }
                root = root.next;
            }
            
            TreeLinkNode dummy = new TreeLinkNode(0);
            if (leftMost != null){
                while (root != null){
                    if (root.left != null){
                        dummy.next = root.left;
                        dummy = dummy.next;
                    }
                    if (root.right != null){
                        dummy.next = root.right;
                        dummy = dummy.next;
                    }
                    root = root.next;
                }
            }
            root = leftMost;
        }
    }

Log in to reply
 

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