/**
* https://leetcode.com/problems/populating-next-right-pointers-in-each-node/#/description
*
*/
#include<iostream>
#include<vector>
#include<stack>
using namespace std;
using vecIter = std::vector<int>::iterator;
struct TreeLinkNode {
int val;
TreeLinkNode *left, *right, *next;
TreeLinkNode(int x) : val(x), left(NULL), right(NULL), next(NULL) {}
};
class Solution
{
public:
Solution(){};
~ Solution(){};
void connect(TreeLinkNode* root){
if(NULL==root) return;
TreeLinkNode* curLev;
while(root->left!=NULL){
curLev=root;
while(curLev!=NULL){
curLev->left->next=curLev->right;
if(curLev->next!=NULL)
curLev->right->next=curLev->next->left;
curLev=curLev->next;
}
root=root->left;
}
}
};
// Test Unit
//
// 1
// / \
// 2 3
// /\ /\
// 4 5 6 7
// /\ /\ /\ /\
// 8 9A BC DE F
// ( A == 10 ...)
TreeLinkNode* createBinaryTree(vecIter beg,vecIter end)
{
vector<TreeLinkNode*> vec;
//把vector数组的int型内容,转化为树结构类型,存到vec数组当中
for(vecIter it=beg;it!=end;++it)
vec.push_back(new TreeLinkNode(*it));
//把vec数组中的结果组织成树的形式
for(int i=0,pos=0;pos!=vec.size()-1;++i)
{
vec[i]->left=vec[++pos];
vec[i]->right=vec[++pos];
}
//返回起始地址
return *vec.begin();
}
//输出节点的内容
void print(TreeLinkNode* root)
{
while(root)
{
cout<<root->val;
TreeLinkNode* cur=root->next;
while(cur)
{
cout<<"->"<<cur->val;
cur=cur->next;
}
cout<<endl;
root=root->left;
}
}
int main(int argc,char** argv){
vector<int> vec={1,2,3,4,5,6,7,8,9,10,11,12,13,14,15};
TreeLinkNode* root=createBinaryTree(vec.begin(),vec.end());
Solution s;
s.connect(root);
print(root);
return 0;
}
leetcode:Populating Next Right Pointers in Each Node
最新推荐文章于 2021-09-24 12:05:40 发布
本文介绍了一个解决方案,用于填充二叉树中每个节点的next指针,使其指向同一层级的下一个节点。通过迭代的方式遍历二叉树的每一层,将每一层的左右子节点的next指针连接起来。
762

被折叠的 条评论
为什么被折叠?



