1s java solution


  • 0
    X

    public void connect(TreeLinkNode root) {
    while (root != null) {
    root = handler(root);
    }
    }

    private TreeLinkNode handler(TreeLinkNode node) {
        TreeLinkNode res = null;
        TreeLinkNode cur = null;
        while(node != null) {
            if (node.left != null) {
                res = node.left;
                break;
            }
            else if (node.right != null) {
                res = node.right;
                break;
            }
            node = node.next;
        }
        
        if (node != null) {
            if (node.left != null) {
                cur = node.left;
                if (node.right != null) {
                    cur.next = node.right;
                    cur = node.right;
                }
            }
            else if (node.right != null) {
                cur = node.right;
            }
            node = node.next;
        }
        
        while (node != null) {
            if (node.left != null) {
                cur.next = node.left;
                cur = node.left;
            }
            if (node.right != null) {
                cur.next = node.right;
                cur = node.right;
            }
            node = node.next;
        }
        return res;
    }

Log in to reply
 

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