算法题--01

01.给出二叉树的 前序数组,和中序数组,请还原二叉树

   思路:按照笔算的思路,从前序节点开始遍历,找到对应节点在中序节点的位置,然后判断出哪些节点是该节点是左子节点,哪些是右子节点,中序又点二分的味道。

    同时,根据中序区分左右,前序遍历的时候,需要跳过已经处理过的节点

import java.util.HashMap;
public class Solution {
    public int[] pre;
    public int[] mid;
    public HashMap<Integer ,Integer> map=new HashMap<>();
    public TreeNode reConstructBinaryTree(int [] pre,int [] in) {
        this.pre=pre;
        this.mid=in;
        for(int i=0;i<in.length;i++){
            map.put(in[i],i);
        }
        
        return pre(0,pre.length-1,0,in.length-1);
    }
    public TreeNode pre(int pi,int pj,int mi,int mj){
        if(mi>mj||pi>pj)
            return null;
        TreeNode node=new TreeNode(pre[pi]);
        int index=map.get(pre[pi]);
        node.left=pre(pi+1,pi+index-mi,mi,index-1);
        node.right=pre(pi+index-mi+1,pj,index+1,mj);
        return node;
        
    }
}
01

 02 链表反转

思路:1.使用栈,全部压进去,然后全部取出来,穿起来

   2.使用三个指中,进行断开操作,从头部开始,(记住尾巴才是null),箭头指向尾巴

public class Solution {
    public ListNode ReverseList(ListNode head) {
        ListNode pre=null;
        ListNode index=head;
        ListNode result=null;
        while(index!=null){
            if(index.next==null){
                result=index;
            }
            //三个指中 一个保存新的节点,两个用来断开,其中一个保存尾巴
            ListNode temp=index.next;
            //交换
            index.next=pre;
            pre=index;
            index=temp;
        }
        return result;
    }
}
02

03 出栈顺序判断

  给出入栈的顺序,再给出出栈的顺序,判断该出栈是否可能是入栈的顺序的结果

public class Solution {
    public boolean IsPopOrder(int [] pushA,int [] popA) {
        if(pushA == null || popA == null || pushA.length == 0 || popA.length == 0 || pushA.length != popA.length) 
            return false;
       Stack<Integer> stack=new Stack<>();
        int i=0;
        int j=0;
        stack.push(pushA[i++]);
        while(j<popA.length){
            while(stack.peek()!=popA[j]){
                if(i==pushA.length)
                    return false;
                stack.push(pushA[i++]);
            }
            //相等就弹出
            if(stack.peek()==popA[j]){
                j++;
                stack.pop();
            }
        }
        return true;
    }
}
03

 

posted @ 2020-09-02 20:12  菜鸟奔跑  阅读(236)  评论(0)    收藏  举报