[LeetCode]Flatten Binary Tree to Linked List
来源:互联网 发布:python 命令行输入 编辑:程序博客网 时间:2024/04/28 22:04
Question
Given a binary tree, flatten it to a linked list in-place.
For example,
Given
1 / \ 2 5 / \ \ 3 4 6
The flattened tree should look like:
1 \ 2 \ 3 \ 4 \ 5 \ 6
本题难度Medium。
链接左右子树法
【复杂度】
时间 O(N) 空间 O(1)
【思路】
如果我们将根节点的右子树接到左子树最后一个节点(就是左子树尽可能靠右下的节点)的右边,那我们可以确定的是,该根节点是已经flat的了。执行完该链接操作,根节点就只有右子树了,这样我们再移动到右子树的根节点,反复执行同样的操作,每次保证一个节点被flat。
【代码】
public class Solution { public void flatten(TreeNode root) { while(root != null){ // 当存在左子树时,说明该节点还没被flat if(root.left != null){ // 找到左子树最后一个节点 TreeNode endOfLeftSubTree = root.left; while(endOfLeftSubTree.right != null){ endOfLeftSubTree = endOfLeftSubTree.right; } // 将右子树加到左子树最后一个节点的右边 endOfLeftSubTree.right = root.right; // 将左子树放到当前节点的右边 root.right = root.left; // 将当前节点左边置空 root.left = null; } // 移动到下一个待flat的节点 root = root.right; } }}
参考
[Leetcode] Flatten Binary Tree to Linked List 整平二叉树
0 0
- LeetCode: Flatten Binary Tree to Linked List
- LeetCode Flatten Binary Tree to Linked List
- LeetCode: Flatten Binary Tree to Linked List
- [Leetcode] Flatten Binary Tree to Linked List
- [LeetCode] Flatten Binary Tree to Linked List
- Leetcode: Flatten Binary Tree to Linked List
- leetcode Flatten Binary Tree to Linked List
- LeetCode Flatten Binary Tree to Linked List
- LeetCode - Flatten Binary Tree to Linked List
- 【leetcode】Flatten Binary Tree to Linked List
- [LeetCode]Flatten Binary Tree to Linked List
- [Leetcode]Flatten Binary Tree to Linked List
- [leetcode]Flatten Binary Tree to Linked List
- LeetCode-Flatten Binary Tree to Linked List
- [leetcode] Flatten Binary Tree to Linked List
- LeetCode - Flatten Binary Tree to Linked List
- LeetCode:Flatten Binary Tree to Linked List
- [LeetCode] Flatten Binary Tree to Linked List
- python3.5 beautiful4.4 扣扣国内新闻 爬虫
- Caused by: org.hibernate.MappingException: Repeated column in mapping for entity: com.yyf.entity.Cus
- Java集合
- sdk+ndk+eclipse搭建android开发环境
- IOS绘制虚线的方法,可以给cell设置虚线分割线
- [LeetCode]Flatten Binary Tree to Linked List
- BLE-CC2640之添加自定义服务
- iOS 自定义多选相册
- Remote development of CUDA Applications CUDA应用远程编译及运行
- 内联成员函数时钟类
- Sublime Text生成html标签快捷键
- 【概率基础】奇异值与特征值(结合LSI)
- 线段树【模板】
- Android之如何随时随地退出程序