Populating Next Right Pointers in Each Node IIspa
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?code
Note:blog
For example,
Given the following binary tree,隊列
1 / \ 2 3 / \ \ 4 5 7
After calling your function, the tree should look like:io
1 -> NULL / \ 2 -> 3 -> NULL / \ \ 4-> 5 -> 7 -> NULL
解答:這題主要思路是層序遍歷,有三種方法實現。function
一種是使用隊列實現,每次記錄隊列的長度(即每層的元素個數),而後彈出相應個數的元素,在此過程當中進行添加下層元素和完成向右指針。class
public class Solution { public void connect(TreeLinkNode root) { if (root == null) return; Queue<TreeLinkNode> q = new LinkedList<TreeLinkNode>(); q.add(root); while (q.size() != 0) { int size = q.size(); for (int i = 0; i < size; i++) { TreeLinkNode temp = q.poll(); if (i != size - 1) temp.next = q.peek(); if (temp.left != null) q.offer(temp.left); if (temp.right != null) q.offer(temp.right); } } } }
另外一種是採用迭代的方法,這種方法無需實現隊列,節省了空間以及入隊和出隊的操做,效率比隊列高。這裏採用了三個節點,cur用來記錄當前節點,head記錄下一層的首節點,prev記錄下一層的上一個遍歷節點。效率
public class Solution { public void connect(TreeLinkNode root) { TreeLinkNode cur = root; TreeLinkNode head = null; TreeLinkNode prev = null; while (cur != null) { while (cur != null) { if (cur.left != null) { if (prev == null) head = cur.left; else prev.next = cur.left; prev = cur.left; } if (cur.right != null) { if (prev == null) head = cur.right; else prev.next = cur.right; prev = cur.right; } cur = cur.next; } cur = head; head = null; prev = null; } } }
第三種方法也是迭代法實現層序遍歷。這種方法採用兩個節點,一個爲傀儡節點,在next中保存下一層的首節點,另外一個爲下一層的當前遍歷節點。採起傀儡節點使得迭代內判斷邏輯變少(無需判斷首節點是否爲空),這種方法比前兩種方法更快。List
public class Solution { public void connect(TreeLinkNode root) { while(root != null){ TreeLinkNode tempChild = new TreeLinkNode(0); TreeLinkNode currentChild = tempChild; while(root!=null){ if(root.left != null) { currentChild.next = root.left; currentChild = currentChild.next;} if(root.right != null) { currentChild.next = root.right; currentChild = currentChild.next;} root = root.next; } root = tempChild.next; } } }