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

👨‍🏫 题目地址

在这里插入图片描述

👩‍🏫 参考题解

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

/**
 * 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

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;
	}
}

相关推荐

  1. [ Hot100]Day46 展开

    2024-01-04 14:52:03       42 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-01-04 14:52:03       94 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-01-04 14:52:03       101 阅读
  3. 在Django里面运行非项目文件

    2024-01-04 14:52:03       82 阅读
  4. Python语言-面向对象

    2024-01-04 14:52:03       91 阅读

热门阅读

  1. 【WPF.NET开发】WPF中的命令

    2024-01-04 14:52:03       51 阅读
  2. 几种Go语言开发的IDE

    2024-01-04 14:52:03       46 阅读
  3. Moonsong Labs与Web3演变

    2024-01-04 14:52:03       45 阅读
  4. 机器视觉系统选型-选型-总结

    2024-01-04 14:52:03       59 阅读
  5. Web网页开发-CSS高级技巧1-笔记

    2024-01-04 14:52:03       61 阅读
  6. SpringBoot整合resilience4j实现接口限流

    2024-01-04 14:52:03       61 阅读
  7. nginx docker 日志打印请求和响应

    2024-01-04 14:52:03       65 阅读
  8. AOP 有哪些实现方式?

    2024-01-04 14:52:03       62 阅读
  9. 线程池的运行原理和使用案例

    2024-01-04 14:52:03       67 阅读
  10. linux 流量监控

    2024-01-04 14:52:03       63 阅读