IT公司100题-1-二叉树转换为双链表

问题描述:
输入一棵二元查找树,将该二元查找树转换成一个排序的双向链表。
要求不能创建任何新的结点,只调整指针的指向。

    10
   /   \
  6      14
/  \    /   \
4   8 12    16

转换成双向链表
4=6=8=10=12=14=16。

首先我们定义的二元查找树 节点的数据结构如下:

struct BSTreeNode
{
  int m_nValue; // value of node
  BSTreeNode *left; // left child of node
  BSTreeNode *right; // right child of node
};

代码实现:

 1 // 1.cc
 2 // 题目:
 3 // 输入一棵二元查找树,将该二元查找树转换成一个排序的双向链表。
 4 // 要求不能创建任何新的结点,只调整指针的指向。
 5   
 6 //    10
 7 //    / /
 8 //   6  14
 9 // / / / /
10 // 4  8 12 16
11   
12 // 转换成双向链表
13 // 4=6=8=10=12=14=16
14 
15 #include <iostream>
16 using namespace std;
17 
18 typedef struct BSTreeNode {
19     int value;
20     BSTreeNode *left;
21     BSTreeNode *right;
22 } tree_node;
23 
24 // 创建二元查找树
25 void add_BSTree_node(tree_node* &p_current, int value) {
26     if (NULL == p_current) {
27         tree_node *node = new tree_node();
28         node->left = NULL;
29         node->right = NULL;
30         node->value = value;
31         p_current = node;
32     } else {
33         if (p_current->value > value)
34             add_BSTree_node(p_current->left, value);
35         else if (p_current->value < value)             
36             add_BSTree_node(p_current->right, value);
37         else
38             cout << "The value has already in the tree.";     
39     } 
40 
41 } 
42 // 二叉树转双向链表 
43 void tree_to_list(tree_node* root, tree_node* &head, tree_node* &last) 
44 {     
45     //为空,返回
46     if (!root)         
47         return; 
48     //中续遍历子树,针对于每个节点设置节点的left和last->right,同时保存为last
49     tree_to_list(root->left, head, last);
50     root->left = last;
51     if (last)
52         last->right = root;
53     else
54         head = root;
55     last = root;
56     tree_to_list(root->right, head, last);
57 }
58 
59 // 打印双向链表
60 void print_list(tree_node* head) {
61     tree_node* p = head;
62     while (p) {
63         cout << p->value << " ";         
64         p = p->right;
65     }
66     cout << endl;
67 }
68 
69 int main() {
70     tree_node *root = NULL;
71 
72     add_BSTree_node(root, 10);
73     add_BSTree_node(root, 6);
74     add_BSTree_node(root, 14);
75     add_BSTree_node(root, 4);
76     add_BSTree_node(root, 8);
77     add_BSTree_node(root, 12);
78     add_BSTree_node(root, 16);
79 
80     tree_node* head = NULL;
81     tree_node* last = NULL;
82     tree_to_list(root, head, last);
83     print_list(head);
84 }

 

转载自源代码

本文链接地址: http://w.worthsee.com/index.php/1-%e6%8a%8a%e4%ba%8c%e5%85%83%e6%9f%a5%e6%89%be%e6%a0%91%e8%bd%ac%e5%8f%98%

 

 

 

posted on 2014-07-27 11:40  醉清风JM  阅读(199)  评论(0编辑  收藏  举报

导航