【LeetCode 面试经典150题】114. Flatten Binary Tree to Linked List 二叉树展开为链表

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)的方式来展平二叉树为链表。

  1. 递归前序遍历

    • 实现 pre_dfs 函数来递归地遍历树的每个节点。
  2. 处理当前节点

    • 对于每个节点,保存其左右子节点的引用,然后将其插入到前一个处理的节点(temp)的右子节点位置。
  3. 清除左子节点

    • 将当前处理节点的左子节点设置为 nullptr
  4. 更新临时节点

    • 更新 temp 指针指向当前处理的节点的右子节点。
  5. 调用递归函数

    • 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);
    }
};
  • 28
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值