A Simple and Concise Java solution using BFS


  • -1
    K
    public void connect(TreeLinkNode root) {
        
        if (root == null) return;
        
        LinkedList<TreeLinkNode> nodes = new LinkedList<TreeLinkNode>();
        nodes.add(root);
        while (!nodes.isEmpty()) {
            int numNodes = nodes.size();
            for (int i=0; i < numNodes; i++) {
                TreeLinkNode aNode = nodes.removeFirst();
                if (aNode.left  != null) nodes.add(aNode.left);
                if (aNode.right != null) nodes.add(aNode.right);
                if (i < numNodes-1) aNode.next = nodes.peek();
            }
        }
        
    }

Log in to reply
 

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