2012-08-23 5 views
0

이진 트리에서 노드의 공통 조상을 찾는 코드를 작성했지만 LCA 대신 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; }} 
    

은 무엇 코드에 문제가 될 수 있을까?

+2

'그러나 이것은 잘 작동하지 않습니다. '- 발생하는 바람직하지 않은 동작은 무엇입니까? – amit

+0

@amit, 이건 나에게 lca를 돌려주지 않고 대신 null을 돌려 준다. – Manish

+0

알고리즘은 실제로 비효율적이다. 대신 다음 방법을 시도해보십시오. node1과 node2에서 트리의 루트 노드까지 경로를 수집합니다. 그런 다음 마지막 목록에서 두 목록을 비교하여 두 목록에있는 마지막 항목을 찾습니다. 이것은 가장 가까운 공통 조상이고 복잡도는 균형 잡힌 이진 트리에서 O (log n) 인 반면 O (n)에서는 최악의 경우 실행될 수있는 O (depth (tree))입니다. 물론 부모에게 노드를 연결하지 않으면 내 접근 방식이 작동하지 않습니다. – Sebastian

답변

0

나는 그것을 고칠 수 있다고 생각합니다. 내 재귀 findLCA가 뭔가를 반환하는지 확인하기 위해 다른 조건을 추가했습니다. 그렇다면 동일한 가치를 더 반환하여 문제를 해결했습니다. 이 디자인이 괜찮 으면 Plz은 의견을 제공합니다.

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;   
} 
+0

답변으로 추가하는 대신 원래 질문을 업데이트해야합니다. –

+0

@chander, Ok. 알고리즘에 대한 제안? – Manish