Flatten Binary Tree to Linked List

本文介绍了一种将二叉树结构通过特定算法展平为链表的方法。通过迭代和递归两种方式实现,使得每个节点的右子节点指向二叉树前序遍历的下一个节点。

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
Hints:

If you notice carefully in the flattened tree, each node's right child points to the next node of a pre-order traversal.

/**
 * Definition for binary tree
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public void flatten(TreeNode root) {
		// Start typing your Java solution below
		// DO NOT write main() function
		if (root == null)
			return;
		Stack<TreeNode> stack = new Stack<TreeNode>();
		stack.push(root);
		TreeNode node = null;
		while (!stack.isEmpty()) {
			TreeNode cur = stack.pop();
			if (node != null) {
				node.left = null;
				node.right = cur;
			}
			node = cur;
            if (cur.right != null) {
				stack.push(cur.right);
			}
			if (cur.left != null) {
				stack.push(cur.left);
			}
		}
	}
}

A recursive solution.


/**
 * Definition for binary tree
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    TreeNode res = new TreeNode(0);
	Stack<TreeNode> stk = new Stack<TreeNode>();
	public void flatten(TreeNode root){
		// Start typing your Java solution below
		// DO NOT write main() function
		if(root == null)
			return;
		if(root != null){
			res.left = null;
			res.right = root;
            res = root;
		}
		if (root.right != null) {
			stk.push(root.right);
		}
		if (root.left != null) {
			stk.push(root.left);
		}
        if(!stk.isEmpty()){
		    flatten(stk.pop());
	    }
	}
}

这段代码是一个**二叉树展开为链表**的解法,采用的是**后序遍历 + 头插法**的方式,将二叉树就地转换为一个**右偏的单链表**(即所有节点的 `left` 指针为空,`right` 指针指向后继节点)。 --- ## ✅ 问题描述(LeetCode 114. 二叉树展开为链表) 将一个二叉树原地修改为一个右偏的链表,例如: ``` 1 / \ 2 5 / \ \ 3 4 6 ``` 变成: ``` 1 \ 2 \ 3 \ 4 \ 5 \ 6 ``` --- ## ✅ 代码解析 ```cpp class Solution { TreeNode* head; // 用于记录当前链表的头部 public: void flatten(TreeNode* root) { if (root == nullptr) { return; } // 后序遍历:右 -> 左 -> 根 flatten(root->right); flatten(root->left); // 将当前节点插入链表头部 root->left = nullptr; // 左指针置空 root->right = head; // 右指针指向当前链表头 head = root; // 更新链表头为当前节点 } }; ``` --- ## 🧠 通俗解释 想象你是一个木匠,正在把一棵树的枝干**从下到上**、**从右到左**地一根一根地连接起来。 - 先处理右子树,再处理左子树,最后处理当前节点(**后序遍历**)。 - 使用一个 `head` 指针,始终指向链表的头部。 - 每次处理一个节点时,把它插在链表最前面(**头插法**)。 - 插入时,设置 `left = nullptr`,`right = head`,然后更新 `head`。 这样,整个树就被**从下到上地构建出一个右偏的链表**。 --- ## 🔁 举个例子 假设输入如下二叉树: ``` 1 / \ 2 5 / \ \ 3 4 6 ``` 后序遍历顺序为:3 → 4 → 2 → 6 → 5 → 1 构建过程如下: - 处理 3 → 链表:3 - 处理 4 → 链表:4 → 3 - 处理 2 → 链表:2 → 4 → 3 - 处理 6 → 链表:6 → 2 → 4 → 3 - 处理 5 → 链表:5 → 6 → 2 → 4 → 3 - 处理 1 → 链表:1 → 5 → 6 → 2 → 4 → 3 最终变成一个右偏的链表。 --- ## ✅ 时间复杂度 & 空间复杂度 - **时间复杂度**:O(n),每个节点访问一次。 - **空间复杂度**:O(h),递归栈深度,h 是树的高度。 --- ## ✅ 与其它方法的比较 | 方法 | 特点 | |------|------| | 前序遍历 + 重建链表 | 简单直观,但需要额外 O(n) 空间 | | 迭代 + 栈 | 类似前序遍历,需要栈空间 | | 后序遍历 + 头插法(本解法) | 原地修改,空间复杂度 O(h),递归栈开销 | | Morris 遍历 | 空间复杂度 O(1),最优化,但实现较复杂 | --- ###
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值