114. Flatten Binary Tree to Linked List
2016-04-18 02:25
447 查看
Given a binary tree, flatten it to a linked list in-place.
For example,
Given
The flattened tree should look like:
Solution 1
private TreeNode prev = null;
public void flatten(TreeNode root) {
if (root == null)
return;
flatten(root.right);
flatten(root.left);
root.right = prev;
root.left = null;
prev = root;
}
Solution 2
//straight forward
public void flatten2(TreeNode root) {
if (root == null) return;
TreeNode left = root.left;
TreeNode right = root.right;
root.left = null;
flatten(left);
flatten(right);
root.right = left;
TreeNode cur = root;
while (cur.right != null) cur = cur.right;
cur.right = right;
}
Solution 3 DFS stack
//DFS Use a stack
public void flatten3(TreeNode root) {
if (root == null) return;
Stack<TreeNode> stack = new Stack<TreeNode>();
stack.push(root);
while (!stack.isEmpty()){
TreeNode curr = stack.pop();
if (curr.right!=null)
stack.push(curr.right);
if (curr.left!=null)
stack.push(curr.left);
if (!stack.isEmpty())
curr.right = stack.peek();
curr.left = null; // dont forget this!!
}
}
For example,
Given
1 / \ 2 5 / \ \ 3 4 6
The flattened tree should look like:
1 \ 2 \ 3 \ 4 \ 5 \ 6
Solution 1
private TreeNode prev = null;
public void flatten(TreeNode root) {
if (root == null)
return;
flatten(root.right);
flatten(root.left);
root.right = prev;
root.left = null;
prev = root;
}
Solution 2
//straight forward
public void flatten2(TreeNode root) {
if (root == null) return;
TreeNode left = root.left;
TreeNode right = root.right;
root.left = null;
flatten(left);
flatten(right);
root.right = left;
TreeNode cur = root;
while (cur.right != null) cur = cur.right;
cur.right = right;
}
Solution 3 DFS stack
//DFS Use a stack
public void flatten3(TreeNode root) {
if (root == null) return;
Stack<TreeNode> stack = new Stack<TreeNode>();
stack.push(root);
while (!stack.isEmpty()){
TreeNode curr = stack.pop();
if (curr.right!=null)
stack.push(curr.right);
if (curr.left!=null)
stack.push(curr.left);
if (!stack.isEmpty())
curr.right = stack.peek();
curr.left = null; // dont forget this!!
}
}
相关文章推荐
- windows内核编程之如何防止一个相同的程序重复运行
- 第7章 Iptables与Firewalld防火墙。
- windows界面编程之自绘菜单
- Hibernate学习实例:关联表的树状结构设计
- MFC 窗口重绘问题
- 如何将内存中的位图数据绘制在DC上
- c/c++实现浏览器的下载功能
- ubuntu14.04+svn
- Flash builder4.7更新AIR SDK
- 技术回归01-Windows内存分配工具
- apache ant 揭开神秘面纱
- [转]ubuntu中查找软件的安装位置
- 【Leetcode】6.ZigZag Conversion 解题
- PHP基础算法
- 修改Shp文件名称
- 研究界面的三个阶段
- 让PHP开发者事半功倍的十大技巧
- Jquery学习之旅之删除元素
- Android Studio 快捷键
- Unity Manual 笔记01 第一章 使用Unity工作——资源工作流