package org.example;import org.junit.Test;import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;public class Foo{class TreeNode {int value;TreeNode left;TreeNode right;public TreeNode(int value) {this.value &#61; value;}}private TreeNode createBinaryTreeByArray(int[] array, int index) {TreeNode tn &#61; null;if (index<array.length) {int value &#61; array[index];tn &#61; new TreeNode(value);tn.left &#61; createBinaryTreeByArray(array, 2*index&#43;1);tn.right &#61; createBinaryTreeByArray(array, 2*index&#43;2);return tn;}return tn;}TreeNode root;public TreeNode BinaryTree(int[] array) {return root &#61; createBinaryTreeByArray(array, 0);}public TreeNode arraybuildTree(int[] array) {if (array.length &#61;&#61; 0) {return null;}TreeNode root &#61; buildTree(array, 0, array.length-1);return root;}private TreeNode buildTree(int[] array, int start, int end) {if (start > end) {return null;}int mid &#61; start &#43; (end - start) / 2;TreeNode root &#61; new TreeNode(array[mid]);root.left &#61; buildTree(array, start, mid-1);root.right &#61; buildTree(array, mid &#43; 1, end);return root;}Map<Integer, TreeNode> parent &#61; new HashMap<Integer, TreeNode>();Set<Integer> visited &#61; new HashSet<Integer>();public void dfs(TreeNode root) {if (root.left !&#61; null) {parent.put(root.left.value, root);dfs(root.left);}if (root.right !&#61; null) {parent.put(root.right.value, root);dfs(root.right);}}public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {dfs(root);while (p !&#61; null) {visited.add(p.value);p &#61; parent.get(p.value);}while (q !&#61; null) {if (visited.contains(q.value)) {return q;}q &#61; parent.get(q.value);}return null;}&#64;Testpublic void test() {TreeNode root &#61; arraybuildTree(new int[]{1, 2, 3, 4, 5, 6, 7});TreeNode treeNode &#61; lowestCommonAncestor(root, new TreeNode(3), new TreeNode(7));System.out.println(treeNode.value);}}