您的位置:首页 > 其它

将二叉树转换成链表

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);

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: