您的位置:首页 > Web前端

剑指offer-第二天

2016-07-02 10:38 288 查看
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();

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: