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:
For example,
Given the following perfect binary tree,
1 / 2 3 / \ / 4 5 6 7
After calling your function, the tree should look like:
1 -> NULL / 2 -> 3 -> NULL / \ / 4->5->6->7 -> NULL
void Connect(BinTree* root) { if(root == NULL) return ; deque<BinTree*> de; de.push_back(root); int i,level=1; BinTree* cur,*pre; while(!de.empty()) { cur = NULL; pre = NULL; for(i=0;i<level&&!de.empty();i++) { if(pre == NULL) { pre = de.front(); if(pre->left != NULL) de.push_back(pre->left); if(pre->right !=NULL) de.push_back(pre->right); de.pop_front(); cout<<pre->value<<endl; continue; } if(cur == NULL) { cur = de.front(); if(cur->left != NULL) de.push_back(cur->left); if(cur->right !=NULL) de.push_back(cur->right); de.pop_front(); cout<<cur->value<<endl; continue; } pre->next =cur; pre = cur; cur = de.front(); de.pop_front(); if(cur->left != NULL) de.push_back(cur->left); if(cur->right != NULL) de.push_back(cur->right); cout<<cur->value<<endl; } if(cur == NULL) pre->next == NULL; else { pre->next = cur; cur->next == NULL; } level *=2; } }
Populating Next Right Pointers in Each Node--LeetCode
原文地址:http://blog.csdn.net/yusiguyuan/article/details/44985757