标签:
Populating Next Right Pointers in Each Node
问题:
each next pointer to point to its next right node. If there is no next right node, the next pointer should be set to NULL
.
Initially, all next pointers are set to NULL
.
Note:
思路:
采用队列方法,poll队首的同时,加入两个其孩子
核心是记录每一个层次的大小,两层循环,时间复杂度为O(n)
我的代码:
public class Solution { public void connect(TreeLinkNode root) { if(root == null) return ; LinkedList<TreeLinkNode> ll = new LinkedList<TreeLinkNode>() ; ll.add(root) ; while(!ll.isEmpty()) { int size = ll.size() ; TreeLinkNode pre = ll.poll() ; if(pre.left != null) ll.add(pre.left) ; if(pre.right != null) ll.add(pre.right) ; for(int i = 0 ; i < size - 1 ; i++) { TreeLinkNode tmp = ll.poll() ; pre.next = tmp ; if(tmp.left != null) { ll.add(tmp.left) ; } if(tmp.right != null) { ll.add(tmp.right) ; } pre = pre.next ; } pre.next = null ; } } }
他人代码:
public void connect(TreeLinkNode root) { if (root == null) { return; } TreeLinkNode leftEnd = root; while (leftEnd != null && leftEnd.left != null) { TreeLinkNode cur = leftEnd; while (cur != null) { cur.left.next = cur.right; cur.right.next = cur.next == null ? null: cur.next.left; cur = cur.next; } leftEnd = leftEnd.left; } }
学习之处:
Populating Next Right Pointers in Each Node
标签:
原文地址:http://www.cnblogs.com/sunshisonghit/p/4313511.html