Flatten Binary Tree to Linked List
2014.2.13 01:03
Given a binary tree, flatten it to a linked list in-place.
For example,
Given
1 / \ 2 5 / \ \ 3 4 6
The flattened tree should look like:
1 \ 2 \ 3 \ 4 \ 5 \ 6
If you notice carefully in the flattened tree, each node's right child points to the next node of a pre-order traversal.
Solution:
The easy way to solve this problem is by postorder traversal of this tree:
1. Flatten the left subtree.
2. Flatten the right subtree.
3. Connect the root->left subtree->right subtree.
When the left and right subtrees are both flattened, piece them together with the root node to make a complete left-skewed tree.
When connecting them, we have to know the boundary nodes of each part. This can be done by passing two parameters as the left and right borders of the tree. Their values are updated as the recursions are performed.
Total time complexity is O(n). Space complexity is O(n) as well.
As for the non-recursive solution of this problem, well...maybe later.
Accepted code:
1 // 4WA, 1AC, not so easy. 2 /** 3 * Definition for binary tree 4 * struct TreeNode { 5 * int val; 6 * TreeNode *left; 7 * TreeNode *right; 8 * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 9 * }; 10 */ 11 class Solution { 12 public: 13 void flatten(TreeNode *root) { 14 if (root == nullptr) { 15 return; 16 } 17 18 if (root->left == nullptr && root->right == nullptr) { 19 return; 20 } 21 22 TreeNode *left_most, *right_most; 23 24 flattenRecursive(root, left_most, right_most); 25 } 26 private: 27 void flattenRecursive(TreeNode *root, TreeNode *&left_most, TreeNode *&right_most) { 28 if (root->left == nullptr && root->right == nullptr) { 29 left_most = root; 30 right_most = root; 31 return; 32 } 33 34 TreeNode *ll, *lr, *rl, *rr; 35 36 if (root->left != nullptr) { 37 flattenRecursive(root->left, ll, lr); 38 } else { 39 ll = lr = root; 40 } 41 if (root->right != nullptr) { 42 flattenRecursive(root->right, rl, rr); 43 } else { 44 rl = rr = root; 45 } 46 47 TreeNode *ptr; 48 root->left = nullptr; 49 if (ll != root) { 50 root->right = ll; 51 lr->right = nullptr; 52 ptr = lr; 53 } else { 54 ptr = root; 55 } 56 if (rr != root) { 57 ptr->right = rl; 58 } 59 60 left_most = root; 61 if (rr != root) { 62 right_most = rr; 63 } else { 64 right_most = lr; 65 } 66 } 67 };
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· .NET10 - 预览版1新功能体验(一)