Java recursive solution


  • -1

    This is just a simple version of my last post, but it couldn't pass the test, just want to throw some idea.

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

  • 0

    这种方法好像超时了。你可以自己试一试


Log in to reply
 

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