LeetCode 114 Flatten Binary Tree to Linked List
来源:互联网 发布:sql server培训机构 编辑:程序博客网 时间:2024/05/13 02:49
题目
Given a binary tree, flatten it to a linked list in-place.
For example,
Given
1 / \ 2 5 / \ \ 3 4 6The flattened tree should look like:
1 \ 2 \ 3 \ 4 \ 5 \ 6
思路
1 能够想到这其实是中序遍历的变形,就成功一半了。
2 一个节点左边的遍历好,然后处理一下,再遍历右边。
3处理的部分为:这个节点的左边设为null,右边接左边处理好的内容,再接原右边。
4 逻辑清楚了,代码自然也就清楚。
代码
public class Solution { public void flatten(TreeNode root) { if(root ==null){ return ; } TreeNode oldleft = root.left; TreeNode oldright = root.right; root.left = null; flatten(left); if(left!=null){ root.right = left; TreeNode cur = left; while(cur.right!=null){ cur = cur.right; } cur.right = right; } flatten(right); }}
可以用递归算法,更加简洁。看代码就能够理解意思
public class Solution { public void flatten(TreeNode root) { if(root == null){ return; } while(root!=null){ if(root.left!=null){ TreeNode cur = root.left; while(cur.right!=null){ cur = cur.right; } cur.right = root.right; root.right = root.left; root.left =null; } root = root.right; } }}
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
- 配置cuda环境的痛苦经历
- OpenGL ES2.0粒子系统(附有源码)
- 电脑系统维护小知识!——————【Badboy】
- GET和POST可传递的值到底有多大?
- [除錯] XMLHttpRequest undefined
- LeetCode 114 Flatten Binary Tree to Linked List
- Swift调用Objective-C
- scala语言学习笔记
- Myeclipse10配置svn
- SQL笔记(MySQL)
- Java 创建多线程
- 移动应用开发(IOS/android等)中一个通用的图片缓存方案讲解
- 加载GDI画png
- HDU 4832 组合计数dp