LeetCode - Medium - 114. Flatten Binary Tree to Linked List

Topic

  • Tree
  • Depth-first Search

Description

https://leetcode.com/problems/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.

Example 1:

Input: root = [1,2,5,3,4,null,6]
Output: [1,null,2,null,3,null,4,null,5,null,6]

Example 2:

Input: root = []
Output: []

Example 3:

Input: root = [0]
Output: [0]

Constraints:

  • The number of nodes in the tree is in the range [0, 2000].
  • -100 <= Node.val <= 100

Follow up: Can you flatten the tree in-place (with O(1) extra space)?

Analysis

方法一:我写的,用到二叉树前序遍历模式的递归法。

方法二:别人写的,很简洁。

方法三:别人写的,跟方法一的核心思想类似,区别在于本方法只用单一方法就搞定。

方法四:别人写的,迭代法。

Submission

package com.lun.medium;import java.util.LinkedList;import com.lun.util.BinaryTree.TreeNode;public class FlattenBinaryTreeToLinkedList {//方法一:我写的,用到二叉树前序遍历模式的递归法public void flatten(TreeNode root) {flattenHelper(root);}private TreeNode flattenHelper(TreeNode node) {if(node == null)return null;TreeNode left = node.left; TreeNode right = node.right;node.left = null;node.right = flattenHelper(left);TreeNode p = node;while(p.right != null)p = p.right;p.right = flattenHelper(right);    	return node;}//方法二:别人写的,很简洁private TreeNode prev = null;public void flatten2(TreeNode root) {if (root == null)return;flatten2(root.right);flatten2(root.left);root.right = prev;root.left = null;prev = root;}public void setPrevNull() {this.prev = null;}//方法三:别人写的,跟方法一的核心思想类似,区别在于本方法只用单一方法就搞定public void flatten3(TreeNode root) {if (root == null) return;TreeNode left = root.left;TreeNode right = root.right;root.left = null;flatten(left);flatten(right);root.right = left;TreeNode cur = root;while (cur.right != null) cur = cur.right;cur.right = right;}//方法四:别人写的,迭代法public void flatten4(TreeNode root) {if (root == null) return;LinkedList<TreeNode> stk = new LinkedList<>();stk.push(root);while (!stk.isEmpty()){TreeNode curr = stk.pop();if (curr.right!=null)  stk.push(curr.right);if (curr.left!=null)  stk.push(curr.left);if (!stk.isEmpty()) curr.right = stk.peek();curr.left = null;  // dont forget this!! }}}

Test

import static org.junit.Assert.*;
import org.junit.Test;import com.lun.util.BinaryTree;
import com.lun.util.BinaryTree.TreeNode;public class FlattenBinaryTreeToLinkedListTest {@Testpublic void test() {FlattenBinaryTreeToLinkedList obj = new FlattenBinaryTreeToLinkedList();TreeNode root1 = BinaryTree.integers2BinaryTree(1, 2, 5, 3, 4, null, 6);obj.flatten(root1);TreeNode expected1 = BinaryTree.integers2BinaryTree(1, null, 2, null, 3, null, 4, null, 5, null, 6);assertTrue(BinaryTree.equals(root1, expected1));TreeNode root2 = null;obj.flatten(root2);assertNull(root2);TreeNode root3 = BinaryTree.integers2BinaryTree(0);obj.flatten(root3);TreeNode expected3 = BinaryTree.integers2BinaryTree(0);assertTrue(BinaryTree.equals(root3, expected3));}@Testpublic void test2() {FlattenBinaryTreeToLinkedList obj = new FlattenBinaryTreeToLinkedList();TreeNode root1 = BinaryTree.integers2BinaryTree(1, 2, 5, 3, 4, null, 6);obj.flatten2(root1);TreeNode expected1 = BinaryTree.integers2BinaryTree(1, null, 2, null, 3, null, 4, null, 5, null, 6);assertTrue(BinaryTree.equals(root1, expected1));obj.setPrevNull();TreeNode root2 = null;obj.flatten2(root2);assertNull(root2);obj.setPrevNull();TreeNode root3 = BinaryTree.integers2BinaryTree(0);obj.flatten2(root3);TreeNode expected3 = BinaryTree.integers2BinaryTree(0);assertTrue(BinaryTree.equals(root3, expected3));}@Testpublic void test3() {FlattenBinaryTreeToLinkedList obj = new FlattenBinaryTreeToLinkedList();TreeNode root1 = BinaryTree.integers2BinaryTree(1, 2, 5, 3, 4, null, 6);obj.flatten3(root1);TreeNode expected1 = BinaryTree.integers2BinaryTree(1, null, 2, null, 3, null, 4, null, 5, null, 6);assertTrue(BinaryTree.equals(root1, expected1));TreeNode root2 = null;obj.flatten3(root2);assertNull(root2);TreeNode root3 = BinaryTree.integers2BinaryTree(0);obj.flatten3(root3);TreeNode expected3 = BinaryTree.integers2BinaryTree(0);assertTrue(BinaryTree.equals(root3, expected3));}@Testpublic void test4() {FlattenBinaryTreeToLinkedList obj = new FlattenBinaryTreeToLinkedList();TreeNode root1 = BinaryTree.integers2BinaryTree(1, 2, 5, 3, 4, null, 6);obj.flatten4(root1);TreeNode expected1 = BinaryTree.integers2BinaryTree(1, null, 2, null, 3, null, 4, null, 5, null, 6);assertTrue(BinaryTree.equals(root1, expected1));TreeNode root2 = null;obj.flatten4(root2);assertNull(root2);TreeNode root3 = BinaryTree.integers2BinaryTree(0);obj.flatten4(root3);TreeNode expected3 = BinaryTree.integers2BinaryTree(0);assertTrue(BinaryTree.equals(root3, expected3));}
}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/445670.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

简单暴力到dp的优化(入门篇)

上篇&#xff0c;我们提到&#xff0c;遇到问题&#xff0c;首先根据定义写出笨方法&#xff0c;找出依赖关系&#xff08;有些题这一步就不太简单&#xff0c;要自己归纳关系&#xff09;&#xff0c;然后进行优化&#xff0c;下面&#xff0c;我们通过几道此方面的经典的&…

简单暴力到dp的优化(初级篇)

一、一维非脑残 1 一个只包含A、B和C的字符串&#xff0c;如果存在某一段长度为3的连续子串中恰好A、B和C各有一个&#xff0c;那么这个字符串就是纯净的&#xff0c;否则这个字符串就是暗黑的。例如&#xff1a;BAACAACCBAAA 连续子串"CBA"中包含了A,B,C各一个&am…

ccpc河北大学生程序设计竞赛dp小总结

近期题目来自校赛&#xff0c;赛前训练&#xff0c;省赛热身&#xff0c;河北ccpc正式比赛。 题目一&#xff1a; 题目描述&#xff1a; 由于第m个台阶上有好吃的薯条&#xff0c;所以薯片现在要爬一段m阶的楼梯. 薯片每步最多能爬k个阶梯&#xff0c;但是每到了第i个台阶&a…

c语言简便实现链表增删改查

注&#xff1a;单追求代码简洁&#xff0c;所以写法可能有点不标准。 //第一次拿c开始写数据结构&#xff0c;因为自己写的&#xff0c;追求代码量少&#xff0c;和学院ppt不太一样。有错请指出 #include <stdio.h> #include <stdlib.h> #include <string.h>…

第一次课 课上代码

第一次课内容 学习心态及注意事项 信心 谦虚 脚踏实地 多动手 python简介 代码量少&#xff0c;简介&#xff0c;易上手&#xff0c;语法要求不过于严格&#xff0c; Python 库。 速度慢&#xff0c; 不可加密。 输出、变量、输入 数据类型&#xff1a;整数、浮点数…

计算机考研专业课只考一科的学校汇总

下列学校专业课只考1门 &#xff08;每项科目下的学校均按照最新学科评估结果由高到低进行排名&#xff09; C语言程序设计 1. 湖南大学 计算机技术&软工专硕&#xff08;信息科学与工程学院&#xff09; 2. 中国海洋大学 计算机技术&#xff08;01计算机应用技术方向&am…

数组实现栈

学习了改进&#xff0c;利用define typedef比上次写的链表更容易改变功能&#xff0c;方便维护&#xff0c;代码更健壮。 大佬别嫌弃&#xff0c;萌新总是很笨&#xff0c;用typedef都想不到。 #include<stdio.h> #include<stdbool.h> #define maxsize 10 typede…

简单暴力到dp的优化(中级篇)

下面再放三道我比较喜欢的&#xff0c;需要好好写一下的题。 第一题比较水 1. White Cloud is exercising in the playground. White Cloud can walk 1 meters or run k meters per second. Since White Cloud is tired,it cant run for two or more continuous seconds. Whi…

第二次课 课上代码

敲一遍&#xff0c;体会每行代码想表达的意思。 第二讲 创建.py文件 数据类型&#xff1a;布尔(and\or\not) 条件判断语句(if elif else) 列表基础操作&#xff08;特点、创建、增加元素、len()、下标、py切片&#xff09; >>> 5>4 True >>> 4>5 Fa…

第一次课 优秀作业展示

18级河北师大软件编程训练 很多同学非常认真的完成了作业&#xff0c;这里选出比较优秀的作业展示出来。 注&#xff1a;展示顺序不是排名 为了尊重同学们的劳动成果&#xff0c;并没有要代码&#xff0c;只是截图展示。 范天祚 &#xff08;傻兔子&#xff09; 熊静祎&…

dp打开思路:HDU1029 HDU1087 HDU1176 HDU1257 POJ1458(水题不水)

题目&#xff1a;https://vjudge.net/contest/68966#overview HDU - 1029 题意&#xff1a;找出出现次数超过一半的数字 蠢思路&#xff1a;排序找中间 DP&#xff1a;扫一遍一个变量count记录解出现的次数&#xff0c;是当前解就&#xff0c;否则--&#xff0c;count为负就…

dp打开思路2:POJ2533 HDU1114 HDU1260 HDU1160(水题不水)

题目&#xff1a;https://vjudge.net/contest/68966#overview POJ2533 最长上升子序列&#xff0c;很平常的题&#xff0c;但是维持单调队列二分还是值得一贴的&#xff0c;O(nlogn) 关键思想&#xff1a;出现在单调队列里的数都在当前接收的数之前&#xff0c;所以找到最小…

二分查找及一般拓展总结

二分-不止是查找哦 二分过程&#xff1a;首先&#xff0c;假设表中元素是按升序排列&#xff0c;将表中间位置记录的关键字与查找关键字比较&#xff0c;如果两者相等&#xff0c;则查找成功&#xff1b;否则利用中间位置记录将表分成前、后两个子表&#xff0c;如果中间位置记…

第三次课 课上代码

这次可能比较简短&#xff0c;这样也好&#xff0c;可读性比较强。 别问我为什么&#xff0c;我不会告诉你们我把代码关了的哼哼。 简单复习、注意事项及小知识强调讲解 作业讲解 列表的遍历 For循环&#xff08;这个参考切片&#xff0c;视频有详细讲解&#xff0c;一样的…

排序算法基本介绍及python实现(含详细注释)

对数组排序可以说是编程基础中的基础&#xff0c;本文对八种排序方法做简要介绍并用python实现。 代码中注释很全&#xff0c;适合复习和萌新学习。这是刚入学自己写的&#xff0c;可能难免比不上标准的写法&#xff0c;但是懒得改了。 文末会放和排序相关的基本拓展总结链接…

第二次作业 讲解及展示

第二次作业&#xff0c;同学们虽然在认真完成&#xff0c;但是或多或少都出了一些错误&#xff0c;一班张婷&#xff0c;四班武仪人&#xff0c;六班杨泽宇&#xff0c;八班候雯洁&#xff0c;安锦阳&#xff0c;刘净圆&#xff0c;这些同学完成的较为出色&#xff0c;错误较少…

深搜DFS\广搜BFS 图初步入门

首先&#xff0c;不管是BFS还是DFS&#xff0c;由于时间和空间的局限性&#xff0c;它们只能解决数据量比较小的问题。 深搜&#xff0c;顾名思义&#xff0c;它从某个状态开始&#xff0c;不断的转移状态&#xff0c;直到无法转移&#xff0c;然后退回到上一步的状态&#xf…

素数基本(埃氏筛法/线性筛法)

一、检查n是否为素数 最简单思路&#xff1a;所有可能的因数全部试一遍。 int gg(int n) {for(int i2;i<n;i){if((n%i)0)return 0;//有因数就不是素数咯}return 1; } 进一步思考&#xff1a;没必要枚举所有的数&#xff0c;每一个小于n^(1/2)的因数i&#xff0c;一定有一个大…

欧几里得gcd/extend_gcd

正式叙述前还写了一点自己的小感受。 问题&#xff1a;求两个正整数a&#xff0c;b的最大公约数。 大神看来是很简单的问题&#xff0c;但是对于去年夏天刚学python的我来说&#xff0c;这是个很难的问题&#xff0c;还记得当时一晚上睡不着都在想怎么快一点的求出最大公约数…

python基础技巧总结(一)

最近总结一下python基础知识&#xff0c;就暂时弃坑了。 本文总结只属于python的一些骚操作。。。 后面文章自行去博客学习交流 原地交换 Python 提供了一个直观的在一行代码中赋值与交换&#xff08;变量值&#xff09;的方法 x, y 10, 20 print(x, y)x, y y, x print(x…