Skip to content

Latest commit

 

History

History
45 lines (42 loc) · 1.06 KB

116. Populating Next Right Pointers in Each Node.md

File metadata and controls

45 lines (42 loc) · 1.06 KB

Solution1 (iterative)

public class Solution {
    public void connect(TreeLinkNode root) {
        if (root == null)   return;
        TreeLinkNode levelStart = root;
        while (levelStart != null) {
            TreeLinkNode cur = levelStart;
            while (cur != null) {
                if (cur.left != null) {
                    cur.left.next = cur.right;
                }
                if (cur.right != null && cur.next != null) {
                    cur.right.next = cur.next.left;
                }
                cur = cur.next;
            }
            levelStart = levelStart.left;
        }
    }
}

Solution2 (recursion)

public class Solution {
    public void connect(TreeLinkNode root) {
        if (root == null) {
            return;
        }
        if (root.left != null) {
            root.left.next = root.right;
            if (root.next != null) {
                root.right.next = root.next.left;
            }
        }
        connect(root.left);
        connect(root.right);
    }
}

note

  • time O(n) space O(1)