LeetCode Flatten Binary Tree to Linked List
2015-12-01 23:09
323 查看
题目:
Given a binary tree, flatten it to a linked list in-place.
For example,
Given
The flattened tree should look like:
click to show hints.
Hints:
If you notice carefully in the flattened tree, each node's right child points to the next node of a pre-order traversal.
题意:
给一棵二叉树根据其前序遍历的结果重新生成一棵右子树。
题解:
此题,LZ考虑用递归方法首先来前序遍历,得到前序遍历之后的结果,并将这个结果保存在LinkedList中,然后重新将这个树输出,注意在输出树的时候,要当心第一个结点。
主要考虑递归调用来前序遍历。
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
click to show hints.
Hints:
If you notice carefully in the flattened tree, each node's right child points to the next node of a pre-order traversal.
题意:
给一棵二叉树根据其前序遍历的结果重新生成一棵右子树。
题解:
此题,LZ考虑用递归方法首先来前序遍历,得到前序遍历之后的结果,并将这个结果保存在LinkedList中,然后重新将这个树输出,注意在输出树的时候,要当心第一个结点。
public class Solution { LinkedList<Integer> list = new LinkedList<Integer>(); public void flatten(TreeNode root) { if(root == null) return; proorder(root); //TreeNode node = root; Iterator it = list.iterator(); TreeNode node = root; int j = 0; while(it.hasNext()) { if(j != 0) { Integer i = (Integer)it.next(); TreeNode l = new TreeNode(i.intValue()); node.right = l; //这儿每次都得考虑左子树和右子树的情况 node.left = null; node = node.right; //System.out.println(i.intValue()); } else it.next(); j++; } } public void proorder(TreeNode root) { list.add(root.val); if(root.left != null) proorder(root.left); if(root.right != null) proorder(root.right); } }
主要考虑递归调用来前序遍历。
相关文章推荐
- node.js初学(一)
- poj 3311 floyd + 状态
- 小试Unity中OBJ和Scene打包Bundle与加载--wondows平台下
- Jquery为DIV添加点击事件,Jquery为a标签超链接添加点击事件
- ReentrantLock的使用和Condition
- 关于cssReset所需掌握的知识点(一)
- Linux下配置文件读取操作流程及其C代码实现
- 10013---ASM字节码框架
- 大批量、大体积excel文件转版为印刷版pdf:对excel文件格式要求及参数设置(2015/12/03)
- 机器码 与 汇编指令的关系
- Quartz2D初体验(二)
- Java查看动态代理生成的代码
- servlet自动刷新页面(比赛文字直播)
- Netty系列之Netty高性能之道
- 我为什么从程序员转行做了产品经理
- 方正综合网络安全打印系亮相“2015网络与信息安全博览会
- 我的VPS选择之路
- 111、Minimum Depth of Binary Tree
- TensorFlow的代码框架
- Module Zero概览