Given a binary tree
struct TreeLinkNode {
TreeLinkNode *left;
TreeLinkNode *right;
TreeLinkNode *next;
}
?
Populate 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.
解决方案:
publicclass Solution {publicvoid connect(TreeLinkNode root) { if(root==null) return; Queue<TreeLinkNode> queue = new LinkedList<TreeLinkNode>(); queue.add(root); TreeLinkNode current; while(!queue.isEmpty()){ current=queue.remove(); if(current.left==null && current.right==null) continue;
//下面解决非叶子节点的next指针问题 if(current.left!=null && current.right!=null) current.left.next = current.right; if(current.next!=null){ if(current.right==null) current.left.next = current.next.left!=null?current.next.left:current.next.right; else current.right.next = current.next.left!=null?current.next.left:current.next.right; }
//将下一层节点放入队列 if(current.left!=null) queue.add(current.left); if(current.right!=null) queue.add(current.right); } } }
LeetCode#116 Populating Next Right Pointers in Each Node
原文:http://www.cnblogs.com/kevinCK/p/4799191.html