首页 > 代码库 > Populating Next Right Pointers in Each Node
Populating Next Right Pointers in Each Node
Problem:Populating Next Right Pointers in Each Node
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).
class Solution { public: void connect(TreeLinkNode *root) { TreeLinkNode * parent_p, *pCur, *leftmost; if(!root) return; parent_p = root;//保存当前结点的父结点 pCur = root->left;//当前处理结点 leftmost = pCur;//指向每一层最左边的结点 while(pCur) { if(pCur == parent_p->left)//当前结点是其父结点的左孩子 { pCur->next = parent_p->right; pCur = pCur->next; } else if(parent_p->next)//当前结点是其父结点的右孩子,并且父结点的next结点存在 { parent_p =parent_p->next; pCur->next = parent_p->left; pCur = pCur->next; } else//当前层的所有结点全部处理完,转到下一层继续处理 { parent_p = leftmost; leftmost = pCur = parent_p->left; } } } };
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。