当前位置:网站首页>LeetCode 144二叉树的前序遍历、LeetCode 114二叉树展开为链表
LeetCode 144二叉树的前序遍历、LeetCode 114二叉树展开为链表
2022-07-01 03:15:00 【是七叔呀】
LeetCode 144二叉树的前序遍历
题目描述:
给你二叉树的根节点 root ,返回它节点值的 前序 遍历。
示例1:
输入:root = [1,null,2,3]
输出:[1,2,3]
示例 2:
输入:root = []
输出:[]
一、按照访问根节点——左子树——右子树的方式遍历这棵树,而在访问左子树或者右子树的时候,我们按照同样的方式遍历,直到遍历完整棵树。
可通过完整代码:
public List<Integer> preorderTraversal(TreeNode root) {
List<Integer> ans = new ArrayList<>();
preorder(root, ans);
return ans;
}
private void preorder(TreeNode root, List<Integer> ans) {
if (root == null) {
return;
}
ans.add(root.val);
preorder(root.left, ans);
preorder(root.right, ans);
}

LeetCode 114二叉树展开为链表
题目描述:
给你二叉树的根结点 root ,请你将它展开为一个单链表:
展开后的单链表应该同样使用 TreeNode ,其中 right 子指针指向链表中下一个结点,而左子指针始终为 null 。
展开后的单链表应该与二叉树 先序遍历 顺序相同。
示例1:
输入:root = [1,2,5,3,4,null,6]
输出:[1,null,2,null,3,null,4,null,5,null,6]
示例 2:
输入:root = []
输出:[]
一、首先通过当前根节点找到cur左子树前序的最后一个右节点predecessor,将此节点和右子树连接起来;伸展【将curr.left=null;curr.right=next】next就是cur.left;然后继续循环往左遍历,连接,遍历到最后总会伸展完
- 时间复杂度:O(n)。其中 n 是二叉树的节点数。展开为单链表的过程中,需要对每个节点访问一次,在寻找前驱节点的过程中,每个节点最多被额外访问一次。
- 空间复杂度:O(1)




可通过完整代码:
public void flatten(TreeNode root) {
TreeNode curr = root;
while (curr != null) {
if (curr.left != null) {
TreeNode next = curr.left;
TreeNode predecessor = next;
while (predecessor.right != null) {
// 找到cur左子树的前序最后一个节点
predecessor = predecessor.right;
}
predecessor.right = curr.right; // 连接cur子树前序的最后一个节点和右子树
curr.left = null; // 部分伸展
curr.right = next;
}
curr = curr.right; // cur.right也即使是原来cur的左节点,之后继续往左遍历,连接左子树最右边节点和其它部分【遍历到最后总会伸展完】
}
}

边栏推荐
- Cookie&Session
- Elk elegant management server log
- Error accessing URL 404
- Analyze datahub, a new generation metadata platform of 4.7K star
- Hal library setting STM32 interrupt
- 力扣-两数之和
- Split(), split(), slice(), can't you tell?
- How do spark tasks of 10W workers run? (Distributed Computing)
- Detailed explanation of ES6 deconstruction grammar
- 服务器渲染技术jsp
猜你喜欢

家居网购项目

岭回归和lasso回归

Overview of EtherCAT principle

Design practice of current limiting components

Hal library operation STM32 serial port

实战 ELK 优雅管理服务器日志

Redis efficient like and cancel function

Cookie&Session

手把手带你了解一块电路板,从设计到制作(干货)

The value of the second servo encoder is linked to the NC virtual axis of Beifu PLC for display
随机推荐
C语言多线程编程入门学习笔记
[linear DP] longest common subsequence
多元线性回归
Edlines: a real time line segment detector with a false detection control
md5sum操作
BluePrism注册下载并安装-RPA第一章
CX5120控制汇川IS620N伺服报错E15解决方案
split(),splice(),slice()傻傻分不清楚?
Introduction to ieda right click source file menu
数组的includes( )
JS日常开发小技巧(持续更新)
Keil5中如何做到 0 Error(s), 0 Warning(s).
VMware vSphere 6.7 virtualization cloud management 12. Vcsa6.7 update vCenter server license
Leetcode 1482 guess, how about this question?
排序链表(归并排序)
线程数据共享和安全 -ThreadLocal
go实现命令行的工具cli
[reading notes] copywriting realization -- four golden steps for writing effective copywriting
Hal library setting STM32 interrupt
Redis高效点赞与取消功能