117. Populating Next Right Pointers in Each Node IIㄟˋ大
Last updated
Last updated
/**
* 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) {}
* };
*/
class Solution {
public:
void connect(TreeLinkNode *root) {
TreeLinkNode* pHead = new TreeLinkNode(0), *pre = pHead;
while (root) {
//連結同一層的節點
if (root->left) {
pre->next = root->left;
pre = pre->next;
}
if (root->right) {
pre->next = root->right;
pre = pre->next;
}
root = root->next;
//如果同一層搜完了
if (!root) {
root = pHead->next;
pre = pHead;
pHead->next = NULL;
}
}
}
};