当前位置:网站首页>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的左节点,之后继续往左遍历,连接左子树最右边节点和其它部分【遍历到最后总会伸展完】
}
}

边栏推荐
- Install vcenter6.7 [vcsa6.7 (vCenter server appliance 6.7)]
- Example of Huawei operator level router configuration | example of configuring optionc mode cross domain LDP VPLS
- The value of the second servo encoder is linked to the NC virtual axis of Beifu PLC for display
- HTB-Lame
- How to use hybrid format to output ISO files? isohybrid:command not found
- XXL job User Guide
- Introduction to ieda right click source file menu
- How to achieve 0 error (s) and 0 warning (s) in keil5
- EDLines: A real-time line segment detector with a false detection control翻译
- Cookie&Session
猜你喜欢
随机推荐
打包iso文件的话,怎样使用hybrid格式输出?isohybrid:command not found
The value of the second servo encoder is linked to the NC virtual axis of Beifu PLC for display
监听器 Listener
Promise中finally的用法
Redis tutorial
leetcode 1818 绝对值,排序,二分法,最大值
VMware vSphere 6.7 virtualization cloud management 12. Vcsa6.7 update vCenter server license
C语言多线程编程入门学习笔记
Redis分布式锁的8大坑
CX5120控制汇川IS620N伺服报错E15解决方案
C language EXECL function
Chapitre 03 Bar _ Gestion des utilisateurs et des droits
还在浪费脑细胞自学吗,这份面试笔记绝对是C站天花板
The shell script uses two bars to receive external parameters
Hal library operation STM32 serial port
Ultimate dolls 2.0 | encapsulation of cloud native delivery
Hello World generation
多元线性回归
C#实现图的深度优先遍历--非递归代码
File upload and download








