Java实现-将二叉树拆成链表
2017-06-13 20:29
281 查看
将一棵二叉树按照前序遍历拆解成为一个
注意事项
不要忘记将左儿子标记为 null,否则你可能会得到空间溢出或是时间溢出。
您在真实的面试中是否遇到过这个题?
Yes
样例
挑战
不使用额外的空间耗费。
/**
* Definition of TreeNode:
* public class TreeNode {
* public int val;
* public TreeNode left, right;
* public TreeNode(int val) {
* this.val = val;
* this.left = this.right = null;
* }
* }
*/
public class Solution {
/**
* @param root: a TreeNode, the root of the binary tree
* @return: nothing
*/
public void flatten(TreeNode root) {
// write your code here
if(root==null)
return;
Stack<TreeNode> stack=new Stack<TreeNode>();
stack.push(root);
while(!stack.isEmpty()){
TreeNode node=stack.pop();
if(node.right!=null){
stack.push(node.right);
}
if(node.left!=null)
stack.push(node.left);
node.left=null;
if(stack.isEmpty())
node.right=null;
else
node.right=stack.peek();
}
}
}
假链表。所谓的假链表是说,用二叉树的 right 指针,来表示链表中的 next 指针。
注意事项
不要忘记将左儿子标记为 null,否则你可能会得到空间溢出或是时间溢出。
您在真实的面试中是否遇到过这个题?
Yes
样例
1 \ 1 2 / \ \ 2 5 => 3 / \ \ \ 3 4 6 4 \ 5 \ 6
挑战
不使用额外的空间耗费。
/**
* Definition of TreeNode:
* public class TreeNode {
* public int val;
* public TreeNode left, right;
* public TreeNode(int val) {
* this.val = val;
* this.left = this.right = null;
* }
* }
*/
public class Solution {
/**
* @param root: a TreeNode, the root of the binary tree
* @return: nothing
*/
public void flatten(TreeNode root) {
// write your code here
if(root==null)
return;
Stack<TreeNode> stack=new Stack<TreeNode>();
stack.push(root);
while(!stack.isEmpty()){
TreeNode node=stack.pop();
if(node.right!=null){
stack.push(node.right);
}
if(node.left!=null)
stack.push(node.left);
node.left=null;
if(stack.isEmpty())
node.right=null;
else
node.right=stack.peek();
}
}
}
相关文章推荐
- 数据结构与算法分析笔记与总结(java实现)--二叉树22:二叉搜索树与双向链表
- java 链表实现二叉树
- Java二叉树链表的简单实现(保存和取出)
- Java中链表、堆栈、队列、二叉树、散列表等数据结构的实现
- 数据结构:二叉树的二叉链表存储--Java实现
- 二叉树转化成双链表的JAVA实现
- java实现二叉树的三种遍历方式,并把二叉树转为双向链表,输出二叉树
- java链表的数据结构和二叉树的实现
- 二叉树、list单向链表的实现( python版 Java版)-17-9-18
- 将二叉树结构转换为双向链表 java语言实现
- Java 使用链表实现约瑟夫环
- java实现双向链表
- Java自己实现双向链表LinkList
- Java模拟单向链表和双向链表的实现
- 二叉树基本操作java实现及遍历浅析
- Java链表实现删除重复结点以及合并链表(非递减)
- 链表面试题Java实现【重要】
- 剑指Offer:面试题15——链表中倒数第k个结点(java实现)
- java实现二叉树的构建以及3种遍历方法
- 《剑指offer》问题7 重建二叉树 Java实现