标签:style blog color io div ar leetcode log
Compared with I version, the tree could be incomplete. The only difference is that, we connect current node‘s child to next non-childrenless‘ node‘s first child.
Still, we need calculate from right to left:
class Solution { public: void connect(TreeLinkNode *p) { if (!p) return; if (p->right) { p->right->next = NULL; if (p->next) { TreeLinkNode *pTmp = p->next; while (pTmp) { if (pTmp->left || pTmp->right) break; pTmp = pTmp->next; } if (pTmp) { if (pTmp->left) p->right->next = pTmp->left; else if (pTmp->right) p->right->next = pTmp->right; } } } if (p->left) { if (p->right) p->left->next = p->right; else { TreeLinkNode *pTmp = p->next; while (pTmp) { if (pTmp->left || pTmp->right) break; pTmp = pTmp->next; } if (pTmp) { if (pTmp->left) p->left->next = pTmp->left; else if (pTmp->right) p->left->next = pTmp->right; } } } connect(p->right); connect(p->left); } };
LeetCode "Populating Next Right Pointers in Each Node II",布布扣,bubuko.com
LeetCode "Populating Next Right Pointers in Each Node II"
标签:style blog color io div ar leetcode log
原文地址:http://www.cnblogs.com/tonix/p/3870129.html