面试题50:树中两个节点的最低公共祖先

该题可转化为求俩个链表的公共节点,求出根节点到两个节点的路径,将路径转化为链表,最近的公共节点就是最低公共祖先。

  1. public class offer50 {  
  2.     class TreeNode{  
  3.         int val;  
  4.         TreeNode left;  
  5.         TreeNode right;  
  6.     }  
  7.     boolean getNodePath(TreeNode root,TreeNode p,ArrayList<TreeNode> path){  
  8.         path.add(root);  
  9.         if(root == p){  
  10.             return true;  
  11.         }  
  12.         boolean found = false;  
  13.         while(!found && root!=null){  
  14.             if(root.left!=null) found = getNodePath(root.left,p,path);  
  15.             if(root.right!=null) found = getNodePath(root.right,p,path);  
  16.         }  
  17.         if(!found) path.remove(path.size()-1);  
  18.         return found;  
  19.   
  20.     }  
  21.     TreeNode getLastCommonNode(ArrayList<TreeNode> path1,ArrayList<TreeNode> path2){  
  22.         int i = 0;  
  23.         TreeNode p1 = path1.get(i);  
  24.         TreeNode p2 = path1.get(i);  
  25.         TreeNode last = null;  
  26.         while(p1!=null&&p2!=null){  
  27.             if(p1==p2) last = p1;  
  28.             p1 = path1.get(++i);  
  29.             p2 = path1.get(++i);  
  30.         }  
  31.         return last;  
  32.     }  
  33.   
  34.     TreeNode getLastCommonParent(TreeNode root,TreeNode p1,TreeNode p2){  
  35.         if(root==null||p1==null||p2==nullreturn null;  
  36.         ArrayList<TreeNode> path1 = new ArrayList<TreeNode>();  
  37.         ArrayList<TreeNode> path2 = new ArrayList<TreeNode>();  
  38.         getNodePath(root,p1,path1);  
  39.         getNodePath(root,p2,path2);  
  40.         return getLastCommonNode(path1,path2);  
  41.     }  
  42.   
  43. }  

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值