package com.tree;
public class CommonParent {
public static TreeNode commonParent(TreeNode root, TreeNode A, TreeNode B) {
if(root==null){
return null;
}
if(root==A||root==B){
return root;
}
TreeNode left = commonParent(root.left, A, B);
TreeNode right = commonParent(root.right, A, B);
if(left!=null&&right!=null){//对于一个树结点,在左子树中找到了A,在右子树中找到了B,那说明此结点是公共节点
return root;
}
if(left!=null) return right;//左子树未找到,右子树找到了A或B,那说明右节点是公共节点
if(right!=null) return left;//右子树未找到,左子树找到了A或B,那说明左节点是公共节点
return null;
}
private class TreeNode {
private TreeNode left;
private TreeNode right;
private Integer val;
public TreeNode(Integer val) {
this.val = val;
}
}
}
找树中两个节点最近的公共父节点
最新推荐文章于 2021-10-12 13:14:04 发布