剑指offer-第二天
来源:互联网 发布:南风知我意温南txt 编辑:程序博客网 时间:2024/06/08 17:29
1、重建二叉树
/*
*题目描述:给出某二叉树的前序遍历和中序遍历,重建该二叉树*思路:前序遍历的第一个元素为root元素,然后在中序遍历中扫描所有元素,找到该元素位置
*则该位置之前的为树的左子树,之后的为树的右子树,然后采用递归方式即可实现二叉树的重建
*/
public TreeNode reConstructBinaryTree(int[] pre,int[] in){
TreeNode root=reConstructBinaryTree(pre,0,pre.length-1,in,0,in.length-1);
return root;
}
public TreeNode reConstructBinaryTree(int[] pre,int startpre,int endpre,int[] in
,int startin,int endin){
if(startpre>endpre||startin>endin) return null;
TreeNode root=new TreeNode(pre[startpre]);
for(int i=startin;i<=endin;i++){
if(in[i]==pre[startpre]){
root.left=reConstructBinaryTree(pre,startpre+1,startpre+i-startin,in,
startin,i-1);
root.right=reConstructBinaryTree(pre,startpre+i-startin+1,endpre,in,
i+1,endin);
}
return root;
}
}
2、用两个栈实现一个队列
/*
*题目描述:用两个栈实现一个队列。实现它的两个函数appendTail和deleteHead,分别完成在
*队列尾部插入节点和队列头部删除节点的功能
*/
public class QueueWithTwoStack{
private Stack<String> stack1=new Stack<String>();
private Stack<String> stack2=new Stack<String>();
public void appendTail(String s){
stack1.push(s);
}
public void deleteHead() throws Exception{
if(stack2.isEmpty()){
while(!stack1.isEmpty()){
stack2.push(stack1.pop());
}
}
if(stack2.isEmpty()){
throws new Exception("queue is empty,do not delete");
}
return stack2.pop();
}
}
0 0
- 剑指offer第二天
- 剑指offer-第二天
- 剑指offer 第二章
- 剑指offer第二题
- 【剑指offer】第二题
- 《剑指Offer》第二章
- 阅读《剑指offer》第二章
- 《剑指offer》学习心得第二日
- 剑指offer 第二章 基础知识
- 剑指offer-第二章-基础篇
- 剑指offer-python代码-第二章
- 剑指offer第二题替换空格
- 剑指Offer读书笔记之第二章2字符替换
- 剑指Offer第二章面试题(Java版)
- 剑指offer第二题【替换空格】c++实现
- 剑指offer第二十七题【字符串的排列】c++实现
- 剑指offer—第二章算法之快速排序
- 剑指Offer(第二版)面试题5:替换空格
- 前端开发者如何与UI设计师沟通
- java中数据文件的下载
- 217. Contains Duplicate
- java中的常用的输入方法
- Windows7+CentOS7 启动项丢失问题解决
- 剑指offer-第二天
- 下拉图片变大
- 拨号盘在下拉通话界面弹出
- 请求自己服务器上的图片
- 【音乐编程】基础知识一
- QQ安全问答
- centos升级python
- 编程之美2.17数组循环移位Java版
- 【转】console.log 用法