1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
| class Solution { LinkedList<Node> queue = new LinkedList<>(); public Node connect(Node root) { if(root == null){ return root; } queue.offer(root); while(!queue.isEmpty()){ int n = queue.size(); Node pre = null; for(int i = 0; i < n; i++){ Node node = queue.poll(); if(pre != null){ pre.next = node; pre = node; }else{ pre = node; } if(node.left != null){ queue.offer(node.left); } if(node.right != null){ queue.offer(node.right); } } pre.next = null; } return root; } }
|