O(1) place, O(N) complexity


  • 0
    B
    public void iterateLevel(TreeLinkNode root) {
        TreeLinkNode last = null;
        do {
            if (root.left != null && root.right != null) {
                root.left.next = root.right;
            }
            if (last != null) {
                if (root.left != null) last.next = root.left; else last.next = root.right;
            }
            last = root.right; if (last == null) last = root.left;
            root = root.next;
            while (root != null && root.left == null && root.right == null) root = root.next;
        } while (root != null);
    }
    public TreeLinkNode findFirstWithChild(TreeLinkNode root) {
        while (root != null && root.left == null && root.right == null) root = root.next;  
        if (root != null) {
            if (root.left != null) {
                return root.left;
            } else {
                return root.right;
            }
        }
        return null;
    }
    public void connect(TreeLinkNode root) {
        if (root == null) return;
        iterateLevel(root);
        
        connect(findFirstWithChild(root));
    }

Log in to reply
 

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