import bean.TreeNode;
import java.util.*;
public class TreeTest {
public static final int PRE_ORDER = 1;
public static final int MID_ORDER = 2;
public static final int AFTER_ORDER = 3;
static List<Integer> preOrder = new ArrayList<>();
static List<Integer> midOrder = new ArrayList<>();
static List<Integer> afterOrder = new ArrayList<>();
public static void main(String[] args) {
TreeNode root = new TreeNode(3);
root.left = new TreeNode(6);
root.right = new TreeNode(5);
root.left.right = new TreeNode(9);
root.right.left = new TreeNode(10);
root.right.right = new TreeNode(20);
new TreeTest().traversal(root);
int[] preArray = new int[preOrder.size()];
for (int i = 0; i < preOrder.size(); i++) {
preArray[i] = preOrder.get(i);
System.out.print(" " + preOrder.get(i));
}
System.out.println();
int[] midArray = new int[midOrder.size()];
for (int i = 0; i < midOrder.size(); i++) {
midArray[i] = midOrder.get(i);
System.out.print(" " + midOrder.get(i));
}
System.out.println();
for (int i = 0; i < afterOrder.size(); i++) {
System.out.print(" " + afterOrder.get(i));
}
// 根据先序和中序重建树
TreeNode rebuild = new TreeNode(preArray[0]);
Map<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < midArray.length; i++) {
map.put(midArray[i], i);
}
Stack<TreeNode> stack = new Stack<>();
stack.push(rebuild);
for (int i = 1; i < preArray.length; i++) {
TreeNode top = stack.peek();
// 栈顶值在mid中的位置
int p = map.get(top.val);
//插入值在mid中的位置
int j = map.get(preArray[i]);
if (j < p) {
top.left = new TreeNode(preArray[i]);
stack.push(top.left);
} else {
TreeNode q = null;
while (!stack.isEmpty() && map.get(stack.peek().val) < j) {
q = stack.pop();
}
q.right = new TreeNode(preArray[i]);
stack.push(q.right);
}
}
System.out.println(isSameTree(root, rebuild));
}
// 判断两棵树是否相同
public static boolean isSameTree(TreeNode a, TreeNode b) {
if (a == null && b == null) {
return true;
}
if (a == null || b == null) {
return false;
}
return a.val == b.val && isSameTree(a.left, b.left) && isSameTree(a.right, b.right);
}
// 树的遍历
public void traversal(TreeNode root) {
if (root == null) {
return;
}
preOrder.add(root.val);
traversal(root.left);
midOrder.add(root.val);
traversal(root.right);
afterOrder.add(root.val);
}
}
重建树
©著作权归作者所有,转载或内容合作请联系作者
- 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
- 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
- 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...