/**
*
* @author gentleKay
* Given a binary tree
* Populate each next pointer to point to its next right node. If there is no next right node, the next pointer should be set toNULL.
* Initially, all next pointers are set toNULL.
* 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* 给定二叉树
* 填充下一个指针以指向其右下一个节点。如果没有下一个右节点,则应将下一个指针设置为tull。
* 最初,所有下一个指针都设置为“否”。
* 注:
* 您只能使用恒定的额外空间。
* 您可以假定它是一个完美的二叉树(即,所有的叶都在同一级别,并且每个父级都有两个子级)。
* 例如,
* 给定以下完美的二叉树,
* 1
/
2 3
/ /
4 5 6 7
* 调用函数后,树应如下所示:
* 1 -> NULL
/
2 -> 3 -> NULL
/ /
4->5->6->7 -> NULLs
*/
根据层次来遍历二叉树,用队列来进行存储节点,来进行遍历。每一层的二叉树都将放入到 list 当中,在遍历 list 进行指针指向下一节点的操作。
import java.util.*; /** * * @author gentleKay * Given a binary tree * Populate each next pointer to point to its next right node. If there is no next right node, the next pointer should be set toNULL. * Initially, all next pointers are set toNULL. * 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 * 给定二叉树 * 填充下一个指针以指向其右下一个节点。如果没有下一个右节点,则应将下一个指针设置为tull。 * 最初,所有下一个指针都设置为“否”。 * 注: * 您只能使用恒定的额外空间。 * 您可以假定它是一个完美的二叉树(即,所有的叶都在同一级别,并且每个父级都有两个子级)。 * 例如, * 给定以下完美的二叉树, * 1 / 2 3 / / 4 5 6 7 * 调用函数后,树应如下所示: * 1 -> NULL / 2 -> 3 -> NULL / / 4->5->6->7 -> NULLs */ public class Main15 { public static void main(String[] args) { TreeLinkNode root = new TreeLinkNode(4); root.left = new TreeLinkNode(2); root.left.left = new TreeLinkNode(1); root.left.right = new TreeLinkNode(3); root.right = new TreeLinkNode(6); root.right.left = new TreeLinkNode(5); root.right.right = new TreeLinkNode(7); Main15.connect(root); } public static class TreeLinkNode { int val; TreeLinkNode left, right, next; TreeLinkNode(int x) { val = x; } } public static void connect(TreeLinkNode root) { if (root == null) { return; } Queue<TreeLinkNode> queue = new LinkedList<>(); queue.add(root); while (!queue.isEmpty()) { ArrayList<TreeLinkNode> array = new ArrayList<>(); int len = queue.size(); for (int i=0;i<len;i++) { TreeLinkNode head = queue.poll(); array.add(head); if (head.left != null) { queue.add(head.left); } if (head.right != null) { queue.add(head.right); } } TreeLinkNode head = array.get(0); for (int i=1;i<array.size();i++) { head.next = array.get(i); head = head.next; } head.next = null; } }