T236 二叉树的最近(深度最大的)公共祖先
时间:2023-10-17 22:07:01
题目要求是深度最大祖先结点!!!而且两者必须有公共祖先结点
/** * 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&&right!=null) return root; if(left!=null) return left; if(right!=null) return right; return null; } }