题目
Follow up for problem "Populating Next Right Pointers in Each Node".
What if the given tree could be any binary tree? Would your previous solution still work?
Note:
For example,
Given the following binary tree,
1 / 2 3 / \ 4 5 7
After calling your function, the tree should look like:
1 -> NULL / 2 -> 3 -> NULL / \ 4-> 5 -> 7 -> NULL分析
用层次遍历的方法可以比较直观的解决这题(解法1)。
由于题目给出了next指针这个辅助空间,我们可以借助这个指针省去层次遍历里的队列,从而实现O(1)空间复杂度的解法(解法2)。
解法1
import java.util.LinkedList; import java.util.Queue; public class PopulatingNextRightPointersInEachNodeII { public void connect(TreeLinkNode root) { if (root == null) { return; } Queue<TreeLinkNode> queue = new LinkedList<TreeLinkNode>(); Queue<TreeLinkNode> nextQueue = new LinkedList<TreeLinkNode>(); queue.add(root); TreeLinkNode left = null; while (!queue.isEmpty()) { TreeLinkNode node = queue.poll(); if (left != null) { left.next = node; } left = node; if (node.left != null) { nextQueue.add(node.left); } if (node.right != null) { nextQueue.add(node.right); } if (queue.isEmpty()) { Queue<TreeLinkNode> temp = queue; queue = nextQueue; nextQueue = temp; left = null; } } } }解法2
public class PopulatingNextRightPointersInEachNodeII { public void connect(TreeLinkNode root) { if (root == null) { return; } TreeLinkNode nextHead = null; TreeLinkNode p = root; TreeLinkNode pre = null; while (p != null) { if (p.left != null) { if (pre == null) { pre = p.left; nextHead = pre; } else { pre.next = p.left; pre = pre.next; } } if (p.right != null) { if (pre == null) { pre = p.right; nextHead = pre; } else { pre.next = p.right; pre = pre.next; } } p = p.next; if (p == null) { p = nextHead; nextHead = null; pre = null; } } } }
LeetCode | Populating Next Right Pointers in Each Node II,布布扣,bubuko.com
LeetCode | Populating Next Right Pointers in Each Node II
原文:http://blog.csdn.net/perfect8886/article/details/20874913