已知前序和中序,重佳二叉树,以层序输出:
import java.util.LinkedList;
import java.util.Queue;
/**
* Created by wqh on 2017/4/23.
*/
public class Num_9 {
public TreeNode reBuildHelper(int[] preOrder, int[] inOrder, int n){
if(n<=0 || preOrder==null || inOrder==null)
return null;
return reBuild(preOrder, 0, preOrder.length-1, inOrder, 0,inOrder.length-1);
}
public TreeNode reBuild(int[] preOrder, int preStart, int preEnd, int[] inOrder, int inStart, int inEnd){
int beginVal = preOrder[preStart];
TreeNode root = new TreeNode(beginVal);
//当只有一个节点时
if(preStart==preEnd)
if(preOrder[preStart] == inOrder[inStart])
return root;
else throw new RuntimeException("preOder is not same with inOrder");
int rootIndex = inStart;
//遍历中序,得到根节点所在索引
while(rootIndex<=preEnd && inOrder[rootIndex]!=beginVal)
rootIndex++;
int leftLen = rootIndex - inStart;
//构建左子树
if(leftLen > 0)
root.left = reBuild(preOrder,preStart+1,preStart+leftLen, inOrder, inStart, rootIndex-1);
//构建右子树
if(inEnd > rootIndex)
root.right = reBuild(preOrder, preStart+leftLen+1, preEnd, inOrder, rootIndex+1, inEnd);
return root;
}
//层序遍历(采用队列的思想)
public void levelOrder(TreeNode root){
Queue<TreeNode> queue = new LinkedList<>();
queue.add(root);
while(!queue.isEmpty()){
TreeNode node = queue.poll();
System.out.print(node.val+" ");
if(node.left != null) queue.add(node.left);
if(node.right != null) queue.add(node.right);
}
}
public static void main(String[] args){
int[] preOrder = new int[]{1,2,4,7,3,5,6,8};
int[] inOrder = new int[]{4,7,2,1,5,3,8,6};
Num_9 test = new Num_9();
TreeNode root = test.reBuildHelper(preOrder, inOrder, preOrder.length);
test.levelOrder(root);
}
}