235LowestCommonAncestorofaBinarySearchTree

题意:输入一个二叉查找树(BST),和两个给定节点,在BST中找到这两个节点的最低的共同的祖先(LCA)。

温馨提示:wiki对LCA的定义为两个节点的最低的祖先,即两个节点到根的首个交点,LCA用在树(计算两个节点之间的距离,即两个节点到根距离的和减去2被的LCA)或者有向无环图。

思路:1、节点的层次,其中,根节点的层次是父节点层次加1(递归定义);

            2、使用HashMap建立节点与直接父节点之间的映射;

            3、两个节点的LCA必定高度相同,使用数据结构stack出栈操作求出LCA。

   public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
    	HashMap
   
   
    
     lineage = new HashMap<>();
    	lineageGen(root, lineage);
    	ArrayList
    
    
     
      stackForP = new ArrayList<>();
    	ArrayList
     
     
      
       stackForQ = new ArrayList<>();
    	pathGen(stackForP, p, lineage);
    	pathGen(stackForQ, q, lineage);
    	int depth1 = stackForP.size(), depth2 = stackForQ.size();
    	int index = (depth1 < depth2) ? depth1 : depth2;
    	for(int i = 0; i < index; i++){
    		TreeNode tmpForP = stackForP.get(depth1 - index + i);
    		TreeNode tmpForQ = stackForQ.get(depth2 - index + i);
    		if(tmpForP.equals(tmpForQ)){
    			return tmpForP; //必然返回
    		}
    	}
    	return root;
    }

   //O(树的深度)
	private void pathGen(ArrayList
      
      
       
        stackForP, TreeNode p, HashMap
       
       
         lineage) { TreeNode tmp = p; stackForP.add(tmp); while((tmp = lineage.get(tmp)) != null){ stackForP.add(tmp); } } //O(n) private void lineageGen(TreeNode root, HashMap 
        
          lineage) {//O(n)不包括root映射 if(root.left != null){ lineage.put(root.left, root); lineageGen(root.left, lineage); } if(root.right != null){ lineage.put(root.right, root); lineageGen(root.right, lineage); } } 
         
       
      
      
     
     
    
    
   
   

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值