114. Flatten Binary Tree to Linked List
题目大意
Given the root of a binary tree, flatten the tree into a “linked list”:
- The “linked list” should use the same
TreeNode
class where the right child pointer points to the next node in the list and the left child pointer is always null. - The “linked list” should be in the same order as a pre-order traversal of the binary tree.
中文释义
给定一个二叉树的根节点,将树展平成一个“链表”:
- “链表”应该使用相同的
TreeNode
类,其中右子指针指向列表中的下一个节点,左子指针始终为 null。 - “链表”应该与二叉树的前序遍历顺序相同。
示例
示例 1:
输入: root
= [1,2,5,3,4,null,6]
输出: [1,null,2,null,3,null,4,null,5,null,6]
示例 2:
输入: root
= []
输出: []
示例 3:
输入: root
= [0]
输出: [0]
限制条件
- 树中节点的数量范围是
[0, 2000]
。 -100 <= Node.val <= 100
进阶
你能原地展平树吗(使用 O(1) 额外空间)?
解题思路
方法
该方法使用前序遍历(Pre-order DFS)的方式来展平二叉树为链表。
-
递归前序遍历:
- 实现
pre_dfs
函数来递归地遍历树的每个节点。
- 实现
-
处理当前节点:
- 对于每个节点,保存其左右子节点的引用,然后将其插入到前一个处理的节点(
temp
)的右子节点位置。
- 对于每个节点,保存其左右子节点的引用,然后将其插入到前一个处理的节点(
-
清除左子节点:
- 将当前处理节点的左子节点设置为
nullptr
。
- 将当前处理节点的左子节点设置为
-
更新临时节点:
- 更新
temp
指针指向当前处理的节点的右子节点。
- 更新
-
调用递归函数:
- 在
flatten
函数中,调用pre_dfs
函数开始递归过程。
- 在
代码
class Solution {
public:
TreeNode* temp = nullptr;
void pre_dfs(TreeNode* root) {
if (root) {
TreeNode* left = root -> left;
TreeNode* right = root -> right;
if (temp == nullptr) {
temp = root;
} else {
temp -> right = root;
temp -> left = nullptr;
temp = temp -> right;
}
pre_dfs(left);
pre_dfs(right);
}
}
void flatten(TreeNode* root) {
pre_dfs(root);
}
};