/**
* 重建二叉树(根据二叉树先序和中序遍历重建二叉树)
* @Description
*/
public class Test05 {
class TreeNode{
int value;
TreeNode left;
TreeNode right;
public TreeNode(int value){
this.value = value;
}
}
public TreeNode buildTree(int[] preorder, int[] inorder) {
if (preorder == null || inorder == null || preorder.length <= 0 || inorder.length <= 0) return null;
return construct(preorder,inorder,0,preorder.length - 1,0,inorder.length - 1);
}
private TreeNode construct(int[] preorder, int[] inorder, int pStart, int pEnd, int iStart, int iEnd) {
//先序遍历的第一个节点为树的根节点
TreeNode root = new TreeNode(preorder[pStart]);
if (pStart == pEnd && iStart == iEnd) return root;
int rootIndex = iStart;
//在中序遍历中找到根节点
while (root.value != inorder[rootIndex] && rootIndex < iEnd){
rootIndex++;
}
int leftLegth = rootIndex - iStart;
if (leftLegth > 0){
//构建左子树
root.left = construct(preorder,inorder,pStart+1,pStart+leftLegth,iStart,rootIndex - 1);
}
if (leftLegth < iEnd - iStart){
//构建右子树
root.right = construct(preorder,inorder,pStart+leftLegth+1,pEnd,rootIndex+1,iEnd);
}
return root;
}
private void preOrderTraverse(TreeNode node) {
if (node == null)
return;
System.out.print(node.value);
preOrderTraverse(node.left);
preOrderTraverse(node.right);
}
private void inOrderTraverse(TreeNode node) {
if (node == null)
return;
inOrderTraverse(node.left);
System.out.print(node.value);
inOrderTraverse(node.right);
}
public static void main(String[] args) {
int[] pre = { 1, 2, 4, 7, 3, 5, 6, 8 };
int[] in = { 4, 7, 2, 1, 5, 3, 8, 6 };
TreeNode root = new Test05().buildTree(pre,in);
new Test05().preOrderTraverse(root);
System.out.println();
new Test05().inOrderTraverse(root);
}
}
剑指Offer-04-重建二叉树
最新推荐文章于 2022-04-18 15:24:45 发布