Accepted solution in Java using Queue Level-order traversal


  • 0
    U
    public void connect(TreeLinkNode root) {
        Queue<TreeLinkNode> qu = new LinkedList<>();
        if(root != null) {
            qu.add(root);
            while (!qu.isEmpty()) {
                int n = qu.size();
                for (int i = 0; i < n; i++) {
                    TreeLinkNode p = qu.remove();
                    if (p.left != null) qu.add(p.left);
                    if (p.right != null) qu.add(p.right);
                    if (i == n - 1) {
                        p.next = null;
                    } else {
                        p.next = qu.peek();
                    }
                }
            }
        }
    }
    

    I solved problem using queue. I think its time-complexity is O(n). Is space-complexity of this O(n)?


Log in to reply
 

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