Java 1ms O(1)space with two pointers


  • 4
    P
    public class Solution {
    public void connect(TreeLinkNode root) {
        if(root == null||root.left == null) return;
        TreeLinkNode nextPointer = root;
        root = root.left;
        TreeLinkNode currentPointer = root;
        while(root!=null){
            while(nextPointer!=null){
                currentPointer.next = nextPointer.right;
                currentPointer = currentPointer.next;
                nextPointer = nextPointer.next;
                if(nextPointer!=null){
                    currentPointer.next = nextPointer.left;
                    currentPointer = currentPointer.next;
                }
                else
                    currentPointer.next = null;
            }
            nextPointer = root;
            root = root.left;
            currentPointer = root;
        }
    }

Log in to reply
 

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