Given a binary treenode
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:spa
1 -> NULL / \ 2 -> 3 -> NULL / \ / \ 4->5->6->7 -> NULL
給定一棵二叉樹,有一個next指針,將它們的每一層連接起來。只能使用常量額外空間,樹是一棵完美二叉樹。.net
將樹的每一層節點用next串起來。這樣每一層也會造成一個單鏈表。而每層的鏈表頭,則是,根的左孩子,左孩子,左孩子。利用雙循環,外層循環,沿着根的左孩子,一直向下。內層循環,負責將下一層的節點串起來。即,將本身右孩子放到左孩子的next上,而右孩子,則可經過本身的next指針,找到右鄰居。指針
樹結點類code
public class TreeLinkNode { TreeLinkNode left; TreeLinkNode right; TreeLinkNode next; }
算法實現類get
public class Solution { public void connect(TreeLinkNode root) { TreeLinkNode node; // 題中假設了輸入的樹是一棵徹底叉樹 // 第一個循環用來處理整個樹 // root.left != null若是不用,則處理到最後第一個沒有左右子樹的結點會出錯 while (root != null && root.left != null) { // 每一個root表示第一個層的第一個結點 // node記錄每個層的第一個結點 node = root; // 處理每一個層 while (node != null) { // 表示鏈接的是同一個結點的下的兩子結點 node.left.next = node.right; // node不是某個層的最後一個結點 if (node.next != null) { // 將這個結點的右子結點鏈接到這個結點的同層相鄰結點的左子結點上 node.right.next = node.next.left; } // 移動到同層的下一個結點 node = node.next; } // 移動到下一層的第一個結點 root = root.left; } } }