My recursive solution (it uses extra mem..) but beats 81% of Java


  • 0
    V
    public void connect(TreeLinkNode root) 
    {
        meth(root, null, 0);
    }
    void meth(TreeLinkNode root, TreeLinkNode parent, int LorR)
    {
        if(root == null)
            return;
        if(LorR == 1)
            root.next = (parent == null || parent.next == null)? null: parent.next.left;
        if(root.left != null && root.right != null)
            root.left.next = root.right;
        meth(root.left, root, 0);
        meth(root.right, root, 1);
    }

  • 0
    J

    Can you give some explanation why It's faster than below approach .
    Here is my solution :

    public void connect(TreeLinkNode root) {
         while(root != null && root.left != null){
            TreeLinkNode tmp = root;
            TreeLinkNode prev = null;
            while(tmp != null){
                tmp.left.next = tmp.right;
                if(prev != null && prev.right != null){
                    prev.right.next = tmp.left;
                }
                prev = tmp;
                tmp = tmp.next;
            }
            root = root.left;
         }
        }

Log in to reply
 

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