剑指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
原创粉丝点击