0

我已经编写了这个解决方案来查找二叉树的 LCA。它给出了更大输入的时间限制。有人可以指出这段代码中的一个问题。这个问题来自 Leetcode OJ。

public class Solution {
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
    if(root == null){
        return null;
    }if((p.val == root.val) || (q.val == root.val)){
        return root;
    } 
    if(root.left == null && root.right == null){
        return null;
    }
    boolean leftChildP = isLeftChild(root,p);
    boolean leftChildQ = isLeftChild(root,q);

    if(isRightChild(root,p) && isLeftChild(root,q)){
        return root;
    }if(isRightChild(root,q) && isLeftChild(root,p)){
        return root;
    }
    if(leftChildP && leftChildQ){
            return lowestCommonAncestor(root.left,p,q);
    }
    return lowestCommonAncestor(root.right,p,q);}


private boolean isLeftChild(TreeNode root, TreeNode node){
    return isChild(root.left,node);
}


private boolean isRightChild(TreeNode root, TreeNode node){
     return isChild(root.right,node);   
}


private boolean isChild(TreeNode parent, TreeNode child){
    if(parent == null){
        return false;}
    if(parent.val == child.val){
        return true;
    }return (isChild(parent.left,child) || isChild(parent.right,child));
}}
4

2 回答 2

1

递归lowestCommonAncestor调用递归isChild......非常简短的检查表明它是 O(n^2)。会很费时间...

尝试构建所有祖先的哈希集p——这可能会花费你 O(n),但通常是 O(logn)。然后从q寻找共同祖先开始遍历。假设在 hashset 中的查找花费 O(1),这将再次花费你 - O(n),但通常是 O(logn)。

你最终会得到典型的 O(logn) 复杂度——这更好......

于 2016-01-25T23:53:13.040 回答
1

您编写的代码的复杂度为 O(n^2)。

您可以通过两种方式在 O(n) 中找到 LCA

1.) 为两个节点(p 和 q)存储根到节点路径(在 ArrayList 中或可以使用哈希集)。现在开始比较从根开始的两条路径中的节点(直到 LCA 应该匹配 p 和 q 的路径),所以在路径中发生不匹配之前的节点将是 LCA。这个解决方案应该在 O(n) 中工作。

2.) 其他解决方案的工作假设是,如果 p 和 q 中只有一个节点退出您的树,那么您的 lca 函数将返回该节点。这是您可以执行的代码

public BinaryTreeNode<Integer> lca(BinaryTreeNode<Integer> root, int data1, int data2){ if(root == null){ return null; } if(root.data == data1 || root.data == data2){ return root; } BinaryTreeNode<Integer> leftAns = lca(root.left, data1 , data2); BinaryTreeNode<Integer> rightAns = lca(root.left, data1 , data2); / // If you are able to find one node in left and the other in right then root is LCA if(leftAns!= null && rightAns != null){ return root; } if(leftAns!=null){ return leftAns; } else{ return rightAns; } }

这也有时间复杂度 O(n)

于 2016-01-26T16:56:40.923 回答