1ms Java Solution


  • 4
    public class Solution {
        int max = 0;
        
        TreeLinkNode findNext(TreeLinkNode node) {
            if(node==null) return null;
            if(node.left != null) return node.left;
            if(node.right != null) return node.right;
            return findNext(node.next);
        }
        
        public void connect(TreeLinkNode root) {
            max = -1;
            connect(root, 0);
        }
        
        public void connect(TreeLinkNode node, int level) {
            
            //base case
            if(node==null) return;
            
            if(level > max) {
                //connect the child nodes at this level
                TreeLinkNode n = node;
                while(n != null) {
                    if(n.left != null) {
                        n.left.next = n.right != null ? n.right : findNext(n.next);
                    }
                    if(n.right != null) {
                        n.right.next = findNext(n.next);
                    }
                    n = n.next;
                }
                max = level;
            }
            
            connect(node.left, level+1);
            connect(node.right, level+1);
        }
    }

Log in to reply
 

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