剑指offer合集

1、替换空格

public class replaceSpace {
    public static String replace(StringBuffer str) {
    	int length=str.length();
    	StringBuffer result=new StringBuffer();
    	for(int i=0;i

2、已知先序遍历和中序遍历,如何求后序遍历

(1)写一个树的类

public class Node{
  Node  left;
  Node  right;
  int value;
  public Node(int value) {
	 this.left=null;
	 this.right=null;
	 this.value=value;
	 }
}

(2)导入树类

import com.offer.Node;
public class BinaryTree {
	private Node root;
	public BinaryTree() {
		root=null;
	}
	
	
	public void postOrder(Node root) {
		if(root!=null) {
			postOrder(root.left);
			postOrder(root.right);
			System.out.println(root.value+" ");
		}	
	}
	
	public void postOrder() {
		this.postOrder(this.root);
	}
	
	
	public void initTree(int[] preOrder,int[] inOrder) {
		root=this.initTree(preOrder,0,preOrder.length-1,inOrder,0,inOrder.length-1);
	}
	
	public Node initTree(int[] preOrder, int start1, int end1, int[] inOrder, int start2, int end2) {
		if(start1>end1||start2>end2) {
			return null;
		}
		
		int rootData=preOrder[start1];
		Node head=new Node(rootData);
		int rootIndex=findIndexInArray(rootData, inOrder, start2, end2);
		int offSet=rootIndex-start2-1;
		Node left=initTree(preOrder, start1+1, start1+1+offSet, inOrder,start2, start2+offSet);
		Node right=initTree(preOrder, start1+2+offSet, end1, inOrder,rootIndex+1, end2);
		head.left=left;
		head.right=right;
		return head;
	}
	
	public int findIndexInArray(int rootData, int[] inOrder, int start2, int end2) {
	    for(int i=start2;i<=end2;i++) {
	    	if(inOrder[i]==rootData) {
	    		return i;
	    	}
	    }
	return -1;
	}


public static void main(String[] args) {
	BinaryTree biTree=new BinaryTree();
	int[] preOrder= {1,2,4,8,9,5,10,3,6,7};
	int[] inOrder= {8,4,9,2,10,5,1,6,3,7};
	biTree.initTree(preOrder,inOrder);
	biTree.postOrder();
}
}

 

你可能感兴趣的:(剑指offer合集)