算法题——二叉树转换为双向链表

何海涛博客:二叉查找树变为排序的双向链表

 

思路:递归。

  • 如果根为空,则直接返回;
  • 先转换左子树,转换成功,则把左子树转换成的链表最后一个节点和根连接;
  • 再转换右子树,把转换后的链表第一个节点和根连接;
  • 最后返回链表头/尾节点。 

 

 1 struct TreeNode
 2 {
 3     int val;
 4     TreeNode *left, *right;
 5 };
 6 
 7 TreeNode *BTree2List(TreeNode *root, bool asRight)
 8 {
 9     if(root == NULL)
10         return NULL;
11 
12     TreeNode *pLeft  = NULL;
13     TreeNode *pRight = NULL;
14 
15     // 转换左子树
16     if(root->left != NULL)
17         pLeft = BTree2List(root->left, false);
18 
19     // 转换成功,和根连接
20     if(pLeft != NULL)
21     {
22         pLeft->right = root;
23         root->left   = pLeft;
24     }
25 
26     // 转换右子树
27     if(root->right != NULL)
28         pRight = BTree2List(root->right, true);
29 
30     // 转换成功,和根连接
31     if(pRight != NULL)
32     {
33         pRight->left = root;
34         root->right  = pRight;
35     }
36 
37     // 如果是右子树,返回链表头;否则返回链表尾部
38     TreeNode *pRet = root;
39 
40     if(asRight)
41     {
42         while(pRet->left != NULL)
43             pRet = pRet->left;
44     }
45     else
46     {
47         while(pRet->right != NULL)
48             pRet = pRet->right;
49     }
50 
51     return pRet;
52 }
53 
54 TreeNode *TreeToList(TreeNode *root)
55 {
56     return BTree2List(root, true);
57 }

 

    原文作者:阿杰的专栏
    原文地址: https://www.cnblogs.com/qieerbushejinshikelou/p/3926916.html
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞