总体思路是递归,将二叉树转换为记录了头尾指针的双向链表,函数如下
void convertTreeToListHelp(TreeNode *root, TreeNode *&head, TreeNode *&tail)
{
head = root;
tail = root;
if (!root) return;
TreeNode *pLeftHead = NULL;
TreeNode *pLeftTail = NULL;
convertTreeToListHelp(root->left, pLeftHead, pLeftTail);
TreeNode *pRightHead = NULL;
TreeNode *pRightTail = NULL;
convertTreeToListHelp(root->right, pRightHead, pRightTail);
if (pLeftTail)
{
head = pLeftHead;
pLeftTail->right = root;
root->left= pLeftTail;
}
if (pRightHead)
{
tail = pRightTail;
root->right = pRightHead;
pRightHead->left = root;
}
}
上述过程稍显罗嗦
更为简洁的方式如下:
TreeNode *head = NULL;
TreeNode *tail = NULL;
TreeNode convertTreeToList(TreeNode *root)
{
If (root == NULL) return NULL;
convertTreeToList(root->left);
Root->left = tail;
if (tail == NULL)
tail = head = root;
else
Tail->right = root;
Tail = root;
convertToList(root->right);
return head;
}
|