題目
Given a binary tree
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:
1 -> NULL
/ \
2 -> 3 -> NULL
/ \ / \
4->5->6->7 -> NULL
解題之法
/**
* Definition for binary tree with next pointer.
* struct TreeLinkNode {
* int val;
* TreeLinkNode *left, *right, *next;
* TreeLinkNode(int x) : val(x), left(NULL), right(NULL), next(NULL) {}
* };
*/
// Recursion, more than constant space
class Solution {
public:
void connect(TreeLinkNode *root) {
if (!root) return;
if (root->left) root->left->next = root->right;
if (root->right) root->right->next = root->next? root->next->left : NULL;
connect(root->left);
connect(root->right);
}
};
分析
這道題實(shí)際上是樹的層序遍歷的應(yīng)用访敌,既然是遍歷,就有遞歸和非遞歸兩種方法,最好兩種方法都要掌握,都要會(huì)寫。下面來看遞歸的解法愁铺,由于是完全二叉樹,所以若節(jié)點(diǎn)的左子結(jié)點(diǎn)存在的話,其右子節(jié)點(diǎn)必定存在独柑,所以左子結(jié)點(diǎn)的next指針可以直接指向其右子節(jié)點(diǎn),對(duì)于其右子節(jié)點(diǎn)的處理方法是私植,判斷其父節(jié)點(diǎn)的next是否為空忌栅,若不為空,則指向其next指針指向的節(jié)點(diǎn)的左子結(jié)點(diǎn)曲稼,若為空則指向NULL索绪。
下面是迭代的方法:
class Solution {
public:
void connect(TreeLinkNode *root) {
if (!root) return;
TreeLinkNode *start = root, *cur = NULL;
while (start->left) {
cur = start;
while (cur) {
cur->left->next = cur->right;
if (cur->next) cur->right->next = cur->next->left;
cur = cur->next;
}
start = start->left;
}
}
};
題目中要求用O(1)的空間復(fù)雜度,所以上面這種方法碉堡了贫悄。用兩個(gè)指針start和cur瑞驱,其中start標(biāo)記每一層的起始節(jié)點(diǎn),cur用來遍歷該層的節(jié)點(diǎn)窄坦,設(shè)計(jì)思路之巧妙唤反,不得不服啊