当前位置:网站首页>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的左节点,之后继续往左遍历,连接左子树最右边节点和其它部分【遍历到最后总会伸展完】
}
}
边栏推荐
猜你喜欢
限流组件设计实战
MySQL knowledge points
Avalanche problem and the use of sentinel
后台系统右边内容如何出现滚动条和解决双滚动条的问题
[linear DP] longest common subsequence
Overview of EtherCAT principle
Redis高效点赞与取消功能
The value of the second servo encoder is linked to the NC virtual axis of Beifu PLC for display
Ridge regression and lasso regression
Edge drawing: a combined real-time edge and segment detector
随机推荐
Introduction to the core functions of webrtc -- an article to understand peerconnectionfactoryinterface rtcconfiguration peerconnectioninterface
Mysql知识点
Best used trust automation script (shell)
数据交换 JSON
过滤器 Filter
JUC learning
How to achieve 0 error (s) and 0 warning (s) in keil5
Overview of EtherCAT principle
leetcode 1818 绝对值,排序,二分法,最大值
[reading notes] copywriting realization -- four golden steps for writing effective copywriting
Introduction and installation of Solr
HTB-Lame
【日常训练】1175. 质数排列
split(),splice(),slice()傻傻分不清楚?
shell脚本使用两个横杠接收外部参数
文件上传下载
实战 ELK 优雅管理服务器日志
EDLines: A real-time line segment detector with a false detection control翻译
Leetcode 1482 guess, how about this question?
打包iso文件的话,怎样使用hybrid格式输出?isohybrid:command not found