一、题目
二、代码
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution
{
//后序遍历就是自下而上
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q)
{
if(root == null) return root;
if(root == p ||root == q ) return root;
//后序遍历 有就汇聚
TreeNode left = lowestCommonAncestor(root.left, p,q);
TreeNode right = lowestCommonAncestor(root.right, p,q);
if(left==null && right == null) return null;
else if(left!=null && right == null) return left;
else if(left==null && right != null) return right;
else
{
return root;
}
}
}
三、运行结果
四、附录
二刷
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution
{
//TreeNode res = null;
//后序遍历 从叶子节点开始
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q)
{
//if(root!=null) System.out.println(" value "+root.val);
if(root==null) return null;
//if(res!=null) return null;
TreeNode left = null;
TreeNode right = null;
if(root.left!=null) left = lowestCommonAncestor(root.left,p,q);
if(root.right!=null) right = lowestCommonAncestor(root.right,p,q);
//下面是处理逻辑
//终止条件在上方
if((left == p||left == q)&&(right == p ||right ==q))
{
// System.out.println(" left "+left.val);
// System.out.println(" right "+right.val);
// res= root;
// return null;
return root;
}
if((root == p||root == q)&&(right == p ||right ==q))
{
// System.out.println(" root "+root.val);
// System.out.println(" right "+right.val);
// res= root;
// return null;
return root;
}
if((left == p||left == q)&&(root == p ||root ==q))
{
// System.out.println(" root "+root.val);
// System.out.println(" left "+left.val);
// res= root;
// return null;
return root;
}
if( root == p || root == q )
{
// System.out.println(" root back "+root.val);
return root;
}
if(left==p || left ==q )
{
// System.out.println(" left back "+ left.val);
return left;
}
if(right == p || right == q)
{
// System.out.println(" right back "+ right.val);
return right;
}
if(left!=null) return left;
if(right!=null) return right;
return null;
}
}