Populating Next Right Pointers in Each Node II
阿新 • • 發佈:2017-06-28
next 存在 root left 並且 找到 題目 else code
題目:
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
題目的大致意思是:使用O(1)的空間對樹進行遍歷,並且設置next指針。因此不能使用遞歸和隊列進行廣度優先搜索。
解題思路: 采用指針,進行二叉樹的廣度優先搜索。總體是設置3個指針,分別為parent, pre, next。
其中parent執行當前要設置next指針的上層節點。pre指向當前要設置next指針的節點, next指向下層的開始節點(因為不是完全二叉樹)
1 /** 2 * Definition for binary tree with next pointer. 3 * public class TreeLinkNode { 4 * int val; 5 * TreeLinkNode left, right, next; 6 * TreeLinkNode(int x) { val = x; } 7 * } 8 */ 9 public class Solution { 10 public void connect(TreeLinkNode root) { 11 if(root == null) { 12 return; 13 } 14 TreeLinkNode pre ;//用於設置next節點 15 TreeLinkNode next ; //標記下一行的開始節點 16 TreeLinkNode parent = root;// 17 18 while(parent != null) { 19 pre = null; 20 next = null; 21 while(parent != null) {//對一行設置next值 22 if (next == null) { //找到parent的下一行第一個節點 23 next = (parent.left != null) ? parent.left : parent.right; 24 } 25 26 if (parent.left != null) { //parent存在子節點 27 if (pre == null) { //如果pre為空,說明parent.left為下一行的第一個節點,因此讓pre指向它 28 pre = parent.left; 29 }else{ //pre不為空,設置pre的next指針 30 pre.next = parent.left; 31 pre = pre.next; 32 } 33 } 34 if (parent.right != null) { 35 if (pre == null) { 36 pre = parent.right; 37 }else{ 38 pre.next = parent.right; 39 pre = pre.next; 40 } 41 } 42 43 parent = parent.next;//遍歷parent的下一個節點 44 } 45 parent = next;//parent指向下一行的開始節點 46 } 47 } 48 }
Populating Next Right Pointers in Each Node II