当前位置: 首页 > news >正文

leetcode 236.二叉树的最近公共祖先

思路一:作者的思路是按照数据结构中学的那样,按照层序遍历的遍历顺序给结点编号,然后每个结点的编号/2就是它的祖先节点,一直往上推,然后将其存储起来,然后在其中找到深度最深并且公有的那个结点就是最近的公共节点。

这个方法放在数据量小的时候是可行的,但是数据量过大,就会时间超时,并且会浪费特别多空间,所以慎重取用。

/*** 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||q==null||p==null)return null;Map<Integer,TreeNode>m_cnt=new HashMap<>();Map<TreeNode,Integer>m_Node=new HashMap<>();int cnt=0;Deque<TreeNode>q1=new LinkedList<>();q1.addLast(root);while(cnt<=100000){TreeNode tmp=q1.getFirst();if(tmp!=null){if(tmp.left!=null)q1.addLast(tmp.left);else if(tmp.left==null)q1.addLast(null);if(tmp.right!=null)q1.addLast(tmp.right);else if(tmp.right==null)q1.addLast(null);}else{q1.addLast(null);q1.addLast(null);}q1.removeFirst();cnt++;m_cnt.put(cnt,tmp);m_Node.put(tmp,cnt);}List<TreeNode>list1=new ArrayList<>();List<TreeNode>list2=new ArrayList<>();int p_cnt=m_Node.get(p);int q_cnt=m_Node.get(q);for(int i=p_cnt;i>0;i/=2){if(m_cnt.get(i)!=null){list1.add(m_cnt.get(i));}}for(int i=q_cnt;i>0;i/=2){if(m_cnt.get(i)!=null){list2.add(m_cnt.get(i));}}if(list1.size()>list2.size()){for(int i=0;i<list1.size();i++){TreeNode t=list1.get(i);if(list2.indexOf(t)>=0){return t;}}}else{for(int i=0;i<list2.size();i++){TreeNode t=list2.get(i);if(list1.indexOf(t)>=0){return t;}}}return null;}
}

思路二:递归。

这个题的递归其实挺难想的,但是大体思路很明确。因为这个递归的过程使用并不与它的真实含义一致。所以我们在递归的时候就会感觉很奇怪。

思路是这样的:我们首先需要知道给出的两个结点在哪。是在当前根节点的左子树还是右子树。如果是分别在两侧,那么当前的根节点就是他们的公共祖先。

如果它们在一侧,我们就对一侧进行递归。

/*** 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||q==root||p==root)return root;TreeNode l=lowestCommonAncestor(root.left,p,q);TreeNode r=lowestCommonAncestor(root.right,p,q);if(l==null)return r;if(r==null)return l;if(l==null&&r==null)return null;return root;}
}


http://www.mrgr.cn/news/34349.html

相关文章:

  • Sentence Transformers 教程!
  • 【解密 Kotlin 扩展函数】扩展函数的底层原理(十八)
  • 云原生周刊:Artifact Hub 成为 CNCF 孵化项目|2024.9.23
  • 项目实现:云备份服务端③(热点模块、服务端业务处理模块实现)
  • 三线城市的女玩家们不想“谈恋爱”,小游戏掘金新蓝海
  • 【Transformers基础入门篇4】基础组件之Model
  • 干货:企业微信批量删除客户指南!
  • 13.第二阶段x86游戏实战2-动态模块地址
  • 【Go】Go语言中深拷贝和浅拷贝
  • Java详细学习路线:从入门到精通的全方位指南
  • 数字人起飞!字节Loopy对口型功能上线 可根据语境匹配表情和情绪
  • 一个可以在线制作样本册,拥有海量样本图册模板可以套用的网站
  • Vert.x,Core - Future
  • 视频无损压缩工具+预览视频生成工具
  • Java 中使用 Gson 实现深度克隆 #什么是深克隆与浅克隆?#clone方法为什么不能直接通过某个对象实例在外部类调用?
  • 我设置了路由器自动切换ip,这会让我的账号登录地址经常改变吗
  • 奔驰「进退」两难
  • Webpack 常见配置项
  • apply、call和bind的作用和区别
  • 装饰器模式