import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class TTTTTTTTT {
public static void main(String[] args) {
TreeNode treeNode1 = new TreeNode(1);
TreeNode treeNode2 = new TreeNode(2);
TreeNode treeNode3 = new TreeNode(3);
TreeNode treeNode4 = new TreeNode(4);
TreeNode treeNode5 = new TreeNode(5);
treeNode1.left = treeNode2;
treeNode1.right = treeNode3;
treeNode2.left = treeNode4;
treeNode2.right = treeNode5;
// TreeNode treeNode = getPath(treeNode1,treeNode4,treeNode5);
//
// System.out.println(treeNode.data);
TreeNode treeNode9 = getPath(treeNode1,treeNode4,treeNode3);
System.out.println(treeNode9.data);
}
static class TreeNode{
int data;
TreeNode left;
TreeNode right;
public TreeNode(int data){
this.data = data;
}
}
public static TreeNode getPath(TreeNode head,TreeNode treeNode1,TreeNode treeNode2){
if(head == null || head == treeNode1 || head == treeNode2){
return head;
}
TreeNode curNode = head;
TreeNode left = null;
TreeNode right = null;
if(curNode.left!=null) {
left = getPath(curNode.left, treeNode1, treeNode2);
}
if(curNode.right!=null) {
right = getPath(curNode.right, treeNode1, treeNode2);
}
if(left!=null && right!=null){
return curNode;
}
return left !=null ? left : right;
}
}
function lowestCommonAncestor( root , o1 , o2 ) {
// 遇到叶子节点返回
if (root === null) {
return null
}
// 如果p或q为根节点,则p或q为最近公共祖先
if (root.val === o1 || root.val === o2) {
return root.val
}
// 在左子树寻找p和q的最近公共祖先
const leftRes = lowestCommonAncestor(root.left, o1, o2)
// 在右子树寻找q和q的最近公共祖先
const rightRes = lowestCommonAncestor(root.right, o1, o2)
// 如果p和q分属两侧,则根节点为最近公共祖先
if (leftRes && rightRes) {
return root.val
}
// 如果左子树有值,则最近公共祖先在左子树,否则,在右子树
return leftRes ? leftRes : rightRes
}