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
.
Note:
- You may only use constant extra space.
- You may assume that it is a perfect binary tree (ie, all leaves are at the same level, and every parent has two children).
For example,
Given the following perfect binary tree,
1 / \ 2 3 / \ / \ 4 5 6 7
After calling your function, the tree should look like:
1 -> NULL / \ 2 -> 3 -> NULL / \ / \ 4->5->6->7 -> NULL
思路:既然该树是一颗完全二叉树,那么每一层除了最右侧的一颗节点之外,所有节点都有一个非空的next兄弟节点,而且:1)如果一个节点是某父节点的left左子节点,那么他的next兄弟节点就是该父节点的right右子节点;2)如果一个节点是某父节点的right右子节点,那么他的next兄弟节点则是该父节点的next兄弟节点的左子节点。即:h.left.next = h.right; h.right.next = h.next.left。
任意一颗节点兄弟节点都与该节点在同一层,显然该使用层序遍历(level order traversal)来解决这个问题。由于二叉树类似于链表(LinkedList),最主要的一个特征是不可随机访问,如果我们需要对第i个节点进行操作,那么我们最好利用第i-1个节点来对他进行操作。在这里我们可以假设,在第i-1层的所有节点都已经标记好各自对应的next兄弟节点,如何处理第i层的节点是我们需要考虑的问题。层序遍历使用队列作为辅助是比较简单的,但该题中有节点有next这个属性,所以我们并不需要借助队列来进行层序遍历,只需要从每层的第一个节点head开始,依次访问其next节点即可,按照上一段中两种情况为其子节点链接next兄弟节点。
/**
* Definition for binary tree with next pointer.
* public class TreeLinkNode {
* int val;
* TreeLinkNode left, right, next;
* TreeLinkNode(int x) { val = x; }
* }
*/
public class Solution {
public void connect(TreeLinkNode root) {
if (root == null) return;
TreeLinkNode head= root, cur = null;
while (head.left != null) {
cur = head;
while (cur != null) {
cur.left.next = cur.right;
if (cur.next != null)
cur.right.next = cur.next.left;
cur = cur.next;
}
head = head.left;
}
}
}