【问题标题】:LCA of Binary Tree Issue二叉树问题的LCA
【发布时间】:2012-08-18 15:05:40
【问题描述】:

我编写了一个代码来查找二叉树中节点的最小共同祖先,但它似乎返回 null 而不是 LCA。

我的算法如下。

  1. 在树的左右分支递归查找祖先
  2. 左树和右树在 LCA 中具有匹配元素的节点。

    public class LCA {
      public static BinaryTreeNode findLCA( BinaryTreeNode root, BinaryTreeNode node1 , BinaryTreeNode node2) {     
    
    if (root == null) {
        return null;
    }       
    
    BinaryTreeNode left = root.getLeft();
    BinaryTreeNode right = root.getRight(); 
    
    if (left != null && (left == node1 || left == node2)) {
        return root;                
    }
    
    if (right != null && (right == node1 || right == node2)) {
        return root;                
    }
    
    if (( findLCA(left, node1, node2) != null) && (findLCA(right, node1, node2) != null)) {         
        return root;
    }
    
    return null; }}
    

这段代码可能有什么问题?

【问题讨论】:

  • but this is not working fine - 您遇到的不良行为是什么?
  • @amit,这不是返回 lca 而是返回 null
  • 算法确实效率低下。请尝试以下方法:从 node1 和 node2 收集树中向上到根节点的路径。然后从末尾开始比较两个列表,以找到两个列表中存在的最后一项。这是最近的共同祖先,复杂性只是 O(depth(tree)),在平衡二叉树中是 O(log n),而在最坏的情况下,您的方法可以在 O(n) 中运行。当然,如果您没有从节点到其父节点的反向链接,我的方法将不起作用。
  • @Sebastian,感谢您的 cmets。是的,当我们有反向链接时,这是有道理的。我写的算法是假设没有反向链接。在这种情况下,您想推荐一些其他算法吗?
  • 如果没有反向链接,没有比 O(n) 更好的算法了。但是,如果您计划在同一棵二叉树上多次运行 LCA 算法,那么构建和存储带有反向链接的二叉树可能会更有效。当然,这并不能解决您的问题,此时可能是过度工程。

标签: java algorithm tree binary-tree


【解决方案1】:

我想我可以解决它。我添加了另一个条件来查看我的递归 findLCA 是否正在返回一些东西。如果是这样,我会进一步返回相同的值来解决问题。如果这个设计没问题,请提供你的 cmets。

public static BinaryTreeNode findLCA( BinaryTreeNode root, BinaryTreeNode node1 , BinaryTreeNode node2) {       

    if (root == null) {
        return null;
    }       

    BinaryTreeNode left = root.getLeft();
    BinaryTreeNode right = root.getRight();
    BinaryTreeNode lcaNode1;
    BinaryTreeNode lcaNode2;

    if (left != null && (left == node1 || left == node2)) {
        return root;                
    }

    if (right != null && (right == node1 || right == node2)) {
        return root;                
    }
    lcaNode1 =  findLCA(left, node1, node2);
    lcaNode2 =  findLCA(right, node1, node2);

    if (( lcaNode1 != null) && lcaNode2 != null) {          
        return root;
    }

    if (lcaNode1 != null) {
        return lcaNode1;
    }

    if (lcaNode2 != null) {
        return lcaNode2;
    }       

    return null;        
}

【讨论】:

  • 您应该更新原始问题,而不是将其添加为答案。
  • @chander,好的。对算法有什么建议吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-07-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-05-16
  • 1970-01-01
相关资源
最近更新 更多