首页 > 代码库 > LeetCode "Populating Next Right Pointers in Each Node II"
LeetCode "Populating Next Right Pointers in Each Node II"
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); }};
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。