天天看點

将二叉樹轉換成連結清單

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

}