题目:
输入某二叉树的前序遍历和中序遍历的结果,请重建该二叉树。
-
程序功能: 根据该二叉树的前序遍历和中序遍历的结果,重建该二叉树,并输出其前序遍历、中序遍历、后序遍历的结果。
-
参考代码:
import java.util.Stack;
public class MyTest {
public static void main(String[] args) {
int[] pre = new int[]{1,2,4,7,3,5,6,8};
int[] in = new int[]{4,7,2,1,5,3,8,6};
TreeNode root = reConstructBinaryTree(pre, in);
preOrderTraversalWithStack(root);
System.out.println();
inOrderTraversalWithStack(root);
System.out.println();
postOrderTraversalWithStack(root);
}
private static class TreeNode{
private int data;
private TreeNode leftChild;
private TreeNode rightChild;
public TreeNode(int data){
this.data = data;
}
}
// 重建二叉树(已知前序+中序)
public static TreeNode reConstructBinaryTree(int[] pre, int[] in){
TreeNode root = createBinaryTree(pre, 0, pre.length - 1, in, 0, in.length - 1);
return root;
}
public static TreeNode createBinaryTree(int[] pre, int startPre, int endPre, int[] in, int startIn, int endIn){
if(startPre > endPre || startIn > endIn){
return null;
}
TreeNode node = null;
for(int i = startIn; i <= endIn; i++){
if(pre[startPre] == in[i]){
node = new TreeNode(pre[startPre]);
node.leftChild = createBinaryTree(pre, startPre + 1, startPre + i - startIn, in, startIn, i - 1);
node.rightChild = createBinaryTree(pre, startPre + i - startIn + 1, endPre, in, i + 1, endIn);
}
}
return node;
}
// 前序遍历(非递归)
public static void preOrderTraversalWithStack(TreeNode root){
Stack<TreeNode> stack = new Stack<>();
TreeNode node = root;
while(node != null || !stack.isEmpty()){
while(node != null){
System.out.print(node.data + " ");
stack.push(node);
node = node.leftChild;
}
if(!stack.isEmpty()){
node = stack.pop();
node = node.rightChild;
}
}
}
// 中序遍历(非递归)
public static void inOrderTraversalWithStack(TreeNode root){
Stack<TreeNode> stack = new Stack<>();
TreeNode node = root;
while(node != null || !stack.isEmpty()) {
while (node != null) {
stack.push(node);
node = node.leftChild;
}
if (!stack.isEmpty()) {
node = stack.pop();
System.out.print(node.data + " ");
node = node.rightChild;
}
}
}
// 后序遍历(非递归)
public static void postOrderTraversalWithStack(TreeNode root){
Stack<TreeNode> stack = new Stack<>();
TreeNode node = root;
TreeNode lastVisit = null;
while(node != null || !stack.isEmpty()){
while(node != null){
stack.push(node);
node = node.leftChild;
}
if(!stack.isEmpty()){
node = stack.peek();
if(node.rightChild == null || node.rightChild == lastVisit){
System.out.print(node.data + " ");
lastVisit = stack.pop();
node = null;
}else{
node = node.rightChild;
}
}
}
}
}