java编程实现根据二叉树的先序遍历序列和中序遍历序列来建立两棵二叉树,并判断这两棵二叉树是否相等
时间: 2023-11-23 17:12:26 浏览: 83
思路:
1. 根据先序遍历序列找到根节点,然后在中序遍历序列中找到根节点的位置,从而将中序遍历序列分成左子树序列和右子树序列
2. 根据左子树序列和右子树序列,递归建立左子树和右子树
3. 重复上述步骤建立第二棵二叉树
4. 判断两棵二叉树是否相等,可以采用递归的方法,递归判断左右子树是否相等
代码实现:
```java
import java.util.Arrays;
class TreeNode {
int val;
TreeNode left;
TreeNode right;
public TreeNode(int val) {
this.val = val;
}
}
public class BinaryTree {
public TreeNode buildTree(int[] preorder, int[] inorder) {
if (preorder.length == 0 || inorder.length == 0) {
return null;
}
int rootVal = preorder[0];
TreeNode root = new TreeNode(rootVal);
int rootIndex = 0;
for (int i = 0; i < inorder.length; i++) {
if (inorder[i] == rootVal) {
rootIndex = i;
break;
}
}
int[] leftInorder = Arrays.copyOfRange(inorder, 0, rootIndex);
int[] rightInorder = Arrays.copyOfRange(inorder, rootIndex + 1, inorder.length);
int[] leftPreorder = Arrays.copyOfRange(preorder, 1, rootIndex + 1);
int[] rightPreorder = Arrays.copyOfRange(preorder, rootIndex + 1, preorder.length);
root.left = buildTree(leftPreorder, leftInorder);
root.right = buildTree(rightPreorder, rightInorder);
return root;
}
public boolean isSameTree(TreeNode p, TreeNode q) {
if (p == null && q == null) {
return true;
} else if (p == null || q == null) {
return false;
} else if (p.val != q.val) {
return false;
} else {
return isSameTree(p.left, q.left) && isSameTree(p.right, q.right);
}
}
public static void main(String[] args) {
BinaryTree bt = new BinaryTree();
int[] preorder1 = {1, 2, 4, 5, 3, 6, 7};
int[] inorder1 = {4, 2, 5, 1, 6, 3, 7};
TreeNode root1 = bt.buildTree(preorder1, inorder1);
int[] preorder2 = {1, 2, 4, 5, 3, 6, 7};
int[] inorder2 = {4, 2, 5, 1, 6, 3, 7};
TreeNode root2 = bt.buildTree(preorder2, inorder2);
boolean isEqual = bt.isSameTree(root1, root2);
System.out.println(isEqual);
}
}
```
输出结果为 true,说明两棵二叉树相等。
阅读全文