锐单电子商城 , 一站式电子元器件采购平台!
  • 电话:400-990-0325

T236 二叉树的最近(深度最大的)公共祖先

时间:2023-10-17 22:07:01 t236集成电路

题目要求是深度最大祖先结点!!!而且两者必须有公共祖先结点

/**  * 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;     } } 
锐单商城拥有海量元器件数据手册IC替代型号,打造电子元器件IC百科大全!

相关文章