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:
You may only use constant extra space.
For example,
Given the following binary tree,java
1 / \ 2 3 / \ \ 4 5 7
After calling your function, the tree should look like:node
1 -> NULL / \ 2 -> 3 -> NULL / \ \ 4-> 5 -> 7 -> NULL
给定一棵二叉树,有一个next指针,将它们的每一层连接起来。只能使用常量额外空间,树是一棵任意的二叉树。算法
将树的每一层节点用next串起来。这样每一层也会造成一个单链表。而每层的链表头,则是,根的左孩子,左孩子,左孩子。利用双循环,外层循环,沿着根的左孩子,一直向下。内层循环,负责将下一层的节点串起来。即,将本身右孩子放到左孩子的next上,而右孩子,则可经过本身的next指针,找到右邻居。spa
树结点类.net
public class TreeLinkNode { TreeLinkNode left; TreeLinkNode right; TreeLinkNode next; }
算法实现类,使用常量空间指针
public class Solution { public void connect(TreeLinkNode root) { TreeLinkNode queue = root; TreeLinkNode level = new TreeLinkNode(0); while (queue != null) { level.next = null; TreeLinkNode current = level; while (queue != null) { if (queue.left != null) { current.next = queue.left; current = current.next; } if (queue.right != null) { current.next = queue.right; current = current.next; } queue = queue.next; } queue = level.next; } } }
算法实现类,使用很是量空间code
import java.util.Iterator; import java.util.LinkedList; import java.util.List; public class Solution { public void connect(TreeLinkNode root) { if (root != null) { // 保存结点 List<TreeLinkNode> list = new LinkedList<>(); // 当前处理的结点的前一个结点 TreeLinkNode prev = null; // 当前处理的结点 TreeLinkNode node; // 当前层剩余的结点个数 int curr = 1; // 记录下一层的元素个数 int next = 0; // 根结点入队 list.add(root); // 队列非空 while (list.size() > 0) { // 删除队首元素 node = list.remove(0); // 当前层剩余数减小 curr--; // 左子树非空,左子结点入队 if (node.left != null) { list.add(node.left); next++; } // 右子树非空,右子结点入队 if (node.right != null) { list.add(node.right); next++; } // 若是当前层处理完了 if (curr == 0) { // 对下一层的元素进行串接 Iterator<TreeLinkNode> iterable = list.iterator(); if (iterable.hasNext()) { prev = iterable.next(); while (iterable.hasNext()) { node = iterable.next(); prev.next = node; prev = node; } } // 更新当前层剩余的结点数 curr = next; // 从新统计下层结点数 next = 0; } } } } }