my solution based on Queue


  • 0
    E
    public class Solution {
        public void connect(TreeLinkNode root) {
            if (root == null) return;
            Queue<TreeLinkNode> q = new LinkedList<TreeLinkNode>();
            q.add(root);
            while (!q.isEmpty()) {
                int size = q.size()-1;
                TreeLinkNode pre = q.remove();
                for (int i = 0; i <= size; i++) {
                    if (pre.left != null) q.add(pre.left);
                    if (pre.right != null) q.add(pre.right);
                    if (i == size) {
                        pre.next = null;
                        break;
                    }
                    TreeLinkNode then = q.remove();
                    pre.next = then;
                    pre = then;
                } 
            }
        }
    }
    

Log in to reply
 

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