#include<iostream>
#include<vector>
#include<deque>
#include<stack>
using namespace std;
struct TreeNode
{
int val;
TreeNode* left;
TreeNode* right;
TreeNode(int val):val(val),left(NULL),right(NULL){};
};
class Solution
{
public:
void fun(TreeNode* root)
{
if(!root)
return;
deque<TreeNode*>res1;
vector<TreeNode*>result;
result.push_back(root);
res1.push_back(root);
res1.push_back(NULL);
while(!res1.empty())
{
TreeNode* node=res1.front();
res1.pop_front();
if(node)
{
if(node->left)
res1.push_back(node->left);
if(node->right)
res1.push_back(node->right);
node->left=NULL;
node->right=res1.front();
}
else
{
if(!res1.empty())
{
result.push_back(res1.front());
res1.push_back(NULL);
}
}
}
auto head=result.begin();
TreeNode* H=*head;
for(auto head:result)
{
while(head)
{
cout<<head->val<<' ';
head=head->right;
}
cout<<endl;
}
}
};
class Solution2
{
public:
void fun(TreeNode* root)
{
if(!root)
return;
TreeNode* cur=root;
TreeNode* first=NULL;
TreeNode* last=NULL;
while(cur)
{
if(!first)
{
if(cur->left)
first=cur->left;
else if(cur->right)
first=cur->right;
}
if(cur->left)
{
if(last)
last->next=cur->left;
last=cur->left;
}
if(cur->right)
{
if(last)
last->next=cur->right;
last=cur->right;
}
if(cur->next)
cur=cur->next;
else
{
cur=first;
first=NULL;
last=NULL;
}
}
}
};
class Solution3
{
public:
void fun(TreeNode* root)
{
if(!root)
return;
TreeNode* cur=root;
while(cur)
{
TreeNode* temp=cur;
while(temp)
{
cout<<temp->val<<' ';
temp=temp->next;
}
cout<<endl;
TreeNode* first=NULL;
TreeNode* last=NULL;
while(cur)
{
if(!first)
{
if(cur->left)
{
first=cur->left;
last=cur->left;
}
else
{
first=cur->right;
last=cur->right;
}
}
if(cur->left&&last!=cur->left)
{
last->next=cur->left;
last=cur->left;
}
if(cur->right&&last!=cur->right)
{
last->next=cur->right;
last=cur->right;
}
cur=cur->next;
}
cur=first;
}
}
};
void main()
{
TreeNode* node1=new TreeNode(1);
TreeNode* node2=new TreeNode(2);
TreeNode* node3=new TreeNode(3);
TreeNode* node4=new TreeNode(4);
TreeNode* node5=new TreeNode(5);
TreeNode* node6=new TreeNode(6);
TreeNode* node7=new TreeNode(7);
node1->left=node2;
node1->right=node3;
node2->left=node4;
node2->right=node5;
node5->right=node7;
/* node3->left=node6;
node3->right=node7;*/
// Solution solution;
//solution.recoverTree(node1);
//solution.recover(node1);
Solution solution;
TreeNode* head;
solution.fun(node1);
}
【leetcode】Populating Next Right Pointers in Each Node II
最新推荐文章于 2021-09-24 12:05:40 发布