将二叉树转换成链表
2014-06-06 14:33
176 查看
struct TreeNode
{
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x):val(x),left(NULL),right(NULL){}
};
TreeNode* convert(TreeNode *root,bool asright)
{
if(root==NULL)
return NULL;
TreeNode *leftpart=convert(root->left,false);
TreeNode *rightpart=convert(root->right,true);
if(leftpart)
{
leftpart->right=root;
root->left=leftpart;
}
if(rightpart)
{
rightpart->left=root;
root->right=rightpart;
}
TreeNode *tmp=root;
if(asright)
{
while(tmp->left)
{
tmp=tmp->left;
}
}
else
{
while(tmp->right)
{
tmp=tmp->right;
}
}
return tmp;
}
TreeNode *converttolist(TreeNode *root)
{
return convert(root,true);
}
{
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x):val(x),left(NULL),right(NULL){}
};
TreeNode* convert(TreeNode *root,bool asright)
{
if(root==NULL)
return NULL;
TreeNode *leftpart=convert(root->left,false);
TreeNode *rightpart=convert(root->right,true);
if(leftpart)
{
leftpart->right=root;
root->left=leftpart;
}
if(rightpart)
{
rightpart->left=root;
root->right=rightpart;
}
TreeNode *tmp=root;
if(asright)
{
while(tmp->left)
{
tmp=tmp->left;
}
}
else
{
while(tmp->right)
{
tmp=tmp->right;
}
}
return tmp;
}
TreeNode *converttolist(TreeNode *root)
{
return convert(root,true);
}
相关文章推荐
- 二叉树与链表之间的转换
- 二叉树转换成双向链表
- 二叉树转换成双向链表
- 将搜索二叉树转换成双向链表
- 把二叉树转换为双向链表
- 面试100题系列之1将查找二叉树转换成有序的双向链表
- 前序和中序重建二叉树、二叉排序树转换为排序的双向链表
- 把二叉树转换成双向链表
- 二叉树--将二叉搜索树转换成一个排序的双向链表
- 将二叉树的叶子结点转换成单链表,并返回最左叶子结点的地址(链头)
- 二叉树转换成双向链表
- 二叉树转换为双向链表,以及二叉树相关操作---纪念考研的时光
- 根据遍历序列构建二叉树,并转换成双向链表
- 二叉树转换为双向链表
- Flatten Binary Tree to Linked List 将二叉树转换为链表
- 将二叉树的叶子结点转换成单链表,并返回最左叶子结点的地址(链头)
- 把搜索二叉树转换成双向链表
- 【遍历二叉树】11把二叉树转换成前序遍历的链表【Flatten Binary Tree to Linked List】
- 二叉树转换为双向链表
- 二叉树转换链表