Simple O(1) space Solution [Java- Recursive]


  • -1
    N
    public TreeLinkNode nextFinder(TreeLinkNode node){
        if(node == null) return null;
        if(node.left != null) return node.left;
        if(node.right != null) return node.right;
        return nextFinder(node.next);
    }
    
    
    public void connect(TreeLinkNode root) {
        if(root != null){
        
        if(root.left != null) root.left.next = root.right;
        if(root.right != null) root.right.next = null;
        
        
        if(root.next != null && root.right != null){
            root.right.next = nextFinder(root.next);
        }else if(root.next != null && root.left != null){
            root.left.next = nextFinder(root.next);
        }
        
        if(root.right != null)  connect(root.right);
        if(root.left != null)  connect(root.left);
    }

  • 0
    D

    recursive solution can't be O(1) space


Log in to reply
 

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