標籤:二叉樹 鏈表 演算法 面試 java
【117-Populating Next Right Pointers in Each Node(二叉樹連結右指標II)】
【LeetCode-面試演算法經典-Java實現】【所有題目目錄索引】
原題
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,
1 / 2 3 / \ 4 5 7
After calling your function, the tree should look like:
1 -> NULL / \ 2 -> 3 -> NULL / \ \ 4-> 5 -> 7 -> NULL
題目大意
給定一棵二叉樹,有一個next指標,將它們的每一層連結起來。只能使用常量額外空間,樹是一棵任意的二叉樹。
解題思路
將樹的每一層節點用next串起來。這樣每一層也會形成一個單鏈表。而每層的鏈表頭,則是,根的左孩子,左孩子,左孩子。利用雙迴圈,外層迴圈,沿著根的左孩子,一直向下。內層迴圈,負責將下一層的節點串起來。即,將自己右孩子放到左孩子的next上,而右孩子,則可通過自己的next指標,找到右鄰居。
代碼實現
樹結點類
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; } }}
演算法實作類別,使用非常量空間
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; } } } }}
評測結果
點擊圖片,滑鼠不釋放,拖動一段位置,釋放後在新的視窗中查看完整圖片。
使用常量空間
使用非常量空間
特別說明
歡迎轉載,轉載請註明出處【http://blog.csdn.net/derrantcm/article/details/47588657】
著作權聲明:本文為博主原創文章,未經博主允許不得轉載。
【LeetCode-面試演算法經典-Java實現】【117-Populating Next Right Pointers in Each Node(二叉樹連結右指標II)】