1 源码java
package classloader.tree;
import java.util.Scanner;
import java.util.*;
import java.util.concurrent.ArrayBlockingQueue;
public class Main {
// 保存父节点
public static Map<Integer, TreeNode> parent = new HashMap<>();
// 保存遍历过的集合
public static Set<Integer> set = new HashSet<>();
public static void main(String[] args) {
//Scanner in = new Scanner(System.in);
//int a = in.nextInt();
//System.out.println(a);
System.out.println("Hello World!");
TreeNode node1 = new TreeNode(10);
TreeNode node2 = new TreeNode(3);
TreeNode node3 = new TreeNode(9);
TreeNode node4 = new TreeNode(1);
TreeNode node5 = new TreeNode(2);
TreeNode node6 = new TreeNode(5);
TreeNode node7 = new TreeNode(7);
node1.left = node2;
node1.right = node3;
node2.left = node4;
node2.right = node5;
node4.left = node6;
node4.right = node7;
int result = findCommonParent(node1, node6, node7);
System.out.print(result);
// 层次顺序遍历(之字形打印)
levelPrint(node1);
}
private static void levelPrint(TreeNode root) {
if(root == null){
return;
}
Queue<TreeNode> queue = new ArrayBlockingQueue<TreeNode>(1000);
queue.add(root);
while(queue.size() > 0){
int thisLevelCount = queue.size();
for(int i = 0; i < thisLevelCount; i++){
TreeNode remove = queue.remove();
System.out.print(remove.value+" ");
if(remove.left != null){
queue.add(remove.left);
}
if(remove.right != null){
queue.add(remove.right);
}
}
System.out.println();
}
}
// 树节点
public static class TreeNode {
public int value;
public TreeNode left;
public TreeNode right;
public TreeNode(int value) {
this.value = value;
}
}
public static int findCommonParent(TreeNode root, TreeNode x, TreeNode y) {
construct(root);
while (x != null) {
// 已遍历的节点值
set.add(x.value);
x = parent.get(x.value);
}
while (y != null) {
if (set.contains(y.value)) {
return y.value;
}
y = parent.get(y.value);
}
return -1;
}
// 按照先序遍历顺序构建parent
public static void construct(TreeNode root) {
if (root.left != null) {
parent.put(root.left.value, root);
construct(root.left);
}
if (root.right != null) {
parent.put(root.right.value, root);
construct(root.right);
}
}
}