资讯详情

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;     } } 

标签: t236集成电路

锐单商城拥有海量元器件数据手册IC替代型号,打造 电子元器件IC百科大全!

锐单商城 - 一站式电子元器件采购平台