Medium!
題目描述:
給定一個二叉樹
struct TreeLinkNode { TreeLinkNode *left; TreeLinkNode *right; TreeLinkNode *next; }
填充它的每個 next 指針,讓這個指針指向其下一個右側節點。如果找不到下一個右側節點,則將 next 指針設置為 NULL
。
初始狀態下,所有 next 指針都被設置為 NULL
。
說明:
- 你只能使用額外常數空間。
- 使用遞歸解題也符合要求,本題中遞歸程序占用的棧空間不算做額外的空間復雜度。
- 你可以假設它是一個完美二叉樹(即所有葉子節點都在同一層,每個父節點都有兩個子節點)。
示例:
給定完美二叉樹,
1 / \ 2 3 / \ / \ 4 5 6 7
調用你的函數后,該完美二叉樹變為:
1 -> NULL / \ 2 -> 3 -> NULL / \ / \ 4->5->6->7 -> NULL
解題思路:
這道題實際上是樹的層序遍歷的應用,可以參考之前的博客Binary Tree Level Order Traversal 二叉樹層序遍歷,既然是遍歷,就有遞歸和非遞歸兩種方法,最好兩種方法都要掌握,都要會寫。
面先來看遞歸的解法,由於是完全二叉樹,所以若節點的左子結點存在的話,其右子節點必定存在,所以左子結點的next指針可以直接指向其右子節點,對於其右子節點的處理方法是,判斷其父節點的next是否為空,若不為空,則指向其next指針指向的節點的左子結點,若為空則指向NULL。
C++解法一:
1 // Recursion, more than constant space 2 class Solution { 3 public: 4 void connect(TreeLinkNode *root) { 5 if (!root) return; 6 if (root->left) root->left->next = root->right; 7 if (root->right) root->right->next = root->next? root->next->left : NULL; 8 connect(root->left); 9 connect(root->right); 10 } 11 };
對於非遞歸的解法要稍微復雜一點,但也不算特別復雜,需要用到queue來輔助,由於是層序遍歷,每層的節點都按順序加入queue中,而每當從queue中取出一個元素時,將其next指針指向queue中下一個節點即可。
C++ 解法二:
1 // Non-recursion, more than constant space 2 class Solution { 3 public: 4 void connect(TreeLinkNode *root) { 5 if (!root) return; 6 queue<TreeLinkNode*> q; 7 q.push(root); 8 q.push(NULL); 9 while (true) { 10 TreeLinkNode *cur = q.front(); 11 q.pop(); 12 if (cur) { 13 cur->next = q.front(); 14 if (cur->left) q.push(cur->left); 15 if (cur->right) q.push(cur->right); 16 } else { 17 if (q.size() == 0 || q.front() == NULL) return; 18 q.push(NULL); 19 } 20 } 21 } 22 };
上面的方法巧妙的通過給queue中添加空指針NULL來達到分層的目的,使每層的最后一個節點的next可以指向NULL,那么我們可以換一種方法來實現分層,我們對於每層的開頭元素開始遍歷之前,先統計一下該層的總個數,用個for循環,這樣for循環結束的時候,我們就知道該層已經被遍歷完了。
C++ 解法三:
1 class Solution { 2 public: 3 void connect(TreeLinkNode *root) { 4 if (!root) return; 5 queue<TreeLinkNode*> q; 6 q.push(root); 7 while (!q.empty()) { 8 int size = q.size(); 9 for (int i = 0; i < size; ++i) { 10 TreeLinkNode *t = q.front(); q.pop(); 11 if (i < size - 1) { 12 t->next = q.front(); 13 } 14 if (t->left) q.push(t->left); 15 if (t->right) q.push(t->right); 16 } 17 } 18 } 19 };
上面三種方法雖然厲害,但是都不符合題意,題目中要求用O(1)的空間復雜度,所以我們來看下面這種碉堡了的方法。用兩個指針start和cur,其中start標記每一層的起始節點,cur用來遍歷該層的節點,設計思路之巧妙,不得不服。
C++ 解法四:
1 class Solution { 2 public: 3 void connect(TreeLinkNode *root) { 4 if (!root) return; 5 TreeLinkNode *start = root, *cur = NULL; 6 while (start->left) { 7 cur = start; 8 while (cur) { 9 cur->left->next = cur->right; 10 if (cur->next) cur->right->next = cur->next->left; 11 cur = cur->next; 12 } 13 start = start->left; 14 } 15 } 16 };