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).
1. BFS: use a queue to keep breadth-first traversal result
/**
* 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) {
// Note: The Solution object is instantiated only once and is reused by each test case.
//breadth-first traversal
queue<TreeLinkNode *> bfsq;
int levelCnt=0;
int level2=0;
if(root==NULL) return;
bfsq.push(root);
levelCnt++;
TreeLinkNode *prevList=NULL;
TreeLinkNode *topS=NULL;
while(!bfsq.empty())
{
topS=bfsq.front();
bfsq.pop();
levelCnt--;
if(topS->left!=NULL && topS->right!=NULL)
{
bfsq.push(topS->left);
level2++;
bfsq.push(topS->right);
level2++;
}
if(prevList!=NULL)
prevList->next=topS;
prevList=topS;
if(levelCnt==0)
{
levelCnt=level2;
level2=0;
prevList=NULL;
}
}
}
};
2. Recursion to save space: populating by level. node->right->next = node->next->left
class Solution {
public:
void connect(TreeLinkNode *root) {
// Note: The Solution object is instantiated only once and is reused by each test case.
if(root==NULL || (root->left==NULL && root->right==NULL) )
return;
root->left->next=root->right;
root->right->next=(root->next)? root->next->left:NULL;
connect(root->left);
connect(root->right);
}
};