力扣hot100 二叉树展开为链表 递归 特殊遍历

👨‍🏫 题目地址

👩‍🏫 参考题解

😋 将左子树插入到右子树上

java 复制代码
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
	public void flatten(TreeNode root)
	{
		while (root != null)
		{
			if (root.left == null)// 找到具有左节点的树
				root = root.right;
			else
			{
				TreeNode pre = root.left;// 当前左子树的先序遍历序列的最后一个结点
				while (pre.right != null)
					pre = pre.right;
				pre.right = root.right;// 将当前右子树接在左子树的最右结点的右孩子上
				root.right = root.left;// 左子树插入当前树的右子树的位置上
				root.left = null;
				root = root.right;// 递归处理每一个拥有左子树的结点
			}
		}
	}
}

👩‍🏫 参考题解

😋 递归

null<-6<-5<-4<-3<-2<-1

java 复制代码
class Solution {
	public void flatten(TreeNode root) {
		helper(root);
	}
	TreeNode pre = null;
	void helper(TreeNode root) {
		if(root==null) {
			return;
		}
		//右节点-左节点-根节点 这种顺序正好跟前序遍历相反
		//用pre节点作为媒介,将遍历到的节点前后串联起来
		helper(root.right);
		helper(root.left);
		root.left = null;
		root.right = pre;
		pre = root;
	}
}
相关推荐
Jack202 小时前
HarmonyOS开发中错误处理策略:网络异常统一处理
算法
小小杨树4 小时前
读懂色彩:拍照调色不再难
算法·计算机视觉·配色
JieE21220 小时前
LeetCode 226. 翻转二叉树|JS 递归超详细拆解,二叉树入门经典题
javascript·算法
JieE21220 小时前
LeetCode 104. 二叉树的最大深度|递归思路超详细拆解
javascript·算法
vivo互联网技术1 天前
CVPR 2026 | 全新强化学习框架 BeautyGRPO:重塑真实人像
算法·大模型·cvpr·影像
Darling噜啦啦1 天前
列表转树算法深度解析:从 Map 到 Reduce 的两种实现,面试高频考点
数据结构·算法·面试
用户497863050731 天前
(一)小红的数组操作
算法·编程语言
怕浪猫1 天前
Electron 系列文章封面图
算法·架构·前端框架
徐小夕1 天前
JitWord 3.0 正式发布,高精度Word异构解析+复杂组件兼容,打造web端协同Word编辑器
前端·vue.js·算法