随笔- 509  文章- 0  评论- 151  阅读- 22万 

2014-04-29 00:15

题目:将二叉搜索树展开成一个双向链表,要求这个链表仍是有序的,而且不能另外分配对象,就地完成。

解法:Leetcode上也有,递归解法。

代码:

复制代码
 1 // 17.13 Flatten a binary search tree into a doubly linked list by inorder traversal order.
 2 // Use postorder traversal to do the flattening job.
 3 #include <cstdio>
 4 using namespace std;
 5 
 6 struct TreeNode {
 7     int val;
 8     TreeNode *left;
 9     TreeNode *right;
10     TreeNode(int _val = 0): val(_val), left(nullptr), right(nullptr) {};
11 };
12 
13 void flatten(TreeNode *&root, TreeNode *&left_most, TreeNode *&right_most)
14 {
15     if (root == nullptr) {
16         left_most = right_most = nullptr;
17         return;
18     }
19     
20     TreeNode *ll, *lr, *rl, *rr;
21     if (root->left != nullptr) {
22         flatten(root->left, ll, lr);
23         root->left = lr;
24         lr->right = root;
25     } else {
26         ll = lr = root;
27     }
28     
29     if (root->right != nullptr) {
30         flatten(root->right, rl, rr);
31         root->right = rl;
32         rl->left = root;
33     } else {
34         rl = rr = root;
35     }
36     
37     left_most = ll;
38     right_most = rr;
39 }
40 
41 void constructBinaryTree(TreeNode *&root)
42 {
43     int val;
44     
45     if (scanf("%d", &val) != 1) {
46         root = nullptr;
47     } else if (val == 0) {
48         root = nullptr;
49     } else {
50         root = new TreeNode(val);
51         constructBinaryTree(root->left);
52         constructBinaryTree(root->right);
53     }
54 }
55 
56 void deleteList(TreeNode *&head)
57 {
58     TreeNode *ptr;
59     
60     while (head != nullptr) {
61         ptr = head;
62         head = head->right;
63         delete ptr;
64     }
65 }
66 
67 int main()
68 {
69     TreeNode *root;
70     TreeNode *left_most, *right_most;
71     TreeNode *head;
72     TreeNode *ptr;
73     
74     while (true) {
75         constructBinaryTree(root);
76         if (root == nullptr) {
77             break;
78         }
79         flatten(root, left_most, right_most);
80         head = left_most;
81         for (ptr = head; ptr != nullptr; ptr = ptr->right) {
82             printf("%d ", ptr->val);
83         }
84         putchar('\n');
85         deleteList(head);
86     }
87     
88     return 0;
89 }
复制代码

 

 posted on   zhuli19901106  阅读(215)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· .NET10 - 预览版1新功能体验(一)
点击右上角即可分享
微信分享提示