0%

[Leetcode]114. Flatten Binary Tree to Linked List(C++)

题目描述

题目链接:114. Flatten Binary Tree to Linked List

Given a binary tree, flatten it to a linked list in-place.

例子

见题目链接。

解题思路

这道题本身要求将二叉树展开变成链表,但是保留二叉树的形式(所有节点只有右子树没有左子树)。展开的过程很容易想到利用递归的方式,先递归展开左子树,再递归展开右子树,当当前节点为叶节点时直接返回即可。这道题难点主要在于如何将展开好的左右子树以正确顺序连接在一起。我的思路是写一个递归函数在展开二叉树之后返回展开之后的链表的尾部节点,这样我们在展开之后既有头节点(原节点)也有尾节点(函数返回的节点),这样连接起来就比较方便了。需要注意考虑左右子树为空子树的情况,代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left),
* right(right) {}
* };
*/
class Solution {
public:
void flatten(TreeNode* root) { flattenTreeNode(root); }

private:
TreeNode* flattenTreeNode(TreeNode* root) {
if (root == nullptr) return nullptr;
if (!root->left && !root->right) return root;

// store left & right subtree to a local var incase we lost it
TreeNode* left = root->left;
TreeNode* right = root->right;

// flattern left subtree, if left is nullptr, the end of left subtree
// would be root
TreeNode* left_end = root;
if (left) left_end = flattenTreeNode(left);

// flatten right subtree, if right is nullptr,
// the end of right subtree would be the end of left subtree
TreeNode* right_end = left_end;
if (right) right_end = flattenTreeNode(right);

// detach left subtree
root->left = nullptr;
// attach left flattened subtree to right of root
root->right = left;
// concatanate right flatterned subtree to the end of left flattened
// subtree
left_end->right = right;

return right_end;
}
};
  • 时间复杂度: O(n)
  • 空间复杂度: O(h) — 递归高度

GitHub 代码同步地址: 114.FlattenBinaryTreeToLinkedList.cpp

其他题目:
GitHub: Leetcode-C++-Solution
博客: Leetcode-Solutions