2017-05-08 3 views
0

를 작동하지 않는 것은 내 B 노드 클래스진 나무 FindParent 방법은 여기

class BNode 
{ 
    public int number; 
    public BNode left; 
    public BNode right; 
    public BNode(int number) 
    { 
     this.number = number; 
    } 
} 

입니다 그리고 여기

다음
public BNode FindParent(BNode BNode, BNode searchNode) 
    { 
     if (searchNode.left == BNode || searchNode.right == BNode) 
     { 
      return searchNode; 
     } 
     if (searchNode.left != null) 
     { 
      return (FindParent(BNode, searchNode.left)); 
     } 
     if (searchNode.right != null) 
     { 
      return (FindParent(BNode, searchNode.right)); 
     } 
     return null; 
    } 

내가

를 호출하는 방법을 BTREE 클래스의 FindParent 방법의 내 구현입니다
BNode bnodeFound = btree.Find(18); 
    BNode bparent = btree.FindParent(bnodeFound, btree.rootNode); 

And here is how the tree looks like

숫자가 트리 루트의 첫 번째 루트를 제외하고 항상 null을 반환합니다. 내가 발견 한 물마루 디버깅은 가장 왼쪽에있는 루트에 가서 올바른 루트가 없다는 것을 확인한 다음 null을 반환한다는 것입니다. 이것을 알아 내려고 노력했지만 성공하지 못했습니다. 비슷한 방법으로 트리의 숫자를 찾으면 그 숫자를 찾을 수 있습니다.

답변

0

왼쪽 노드에 대해 매번 반복적으로 FindParent()을 호출하면 (null이 아닌 경우) 직접 반환합니다. 올바른 노드의 FindParent()은 절대로 호출되지 않습니다.

// Assume we run this for the root node 
if (searchNode.left != null) 
{ 
    // If left node is not null, then it tries to find in left subtree only 
    // Since it returns directly, whether found or not-found it WILL NOT 
    // search in right sub-tree 
    return (FindParent(BNode, searchNode.left)); 
} 

// Unreachable code if left is not NULL 
if (searchNode.right != null) 
{ 
    return (FindParent(BNode, searchNode.right)); 
} 

return 문을 제거하고 여전히 오류가 없는지 확인해보십시오.

if (searchNode.left != null) 
{ 
    var found = (FindParent(BNode, searchNode.left)); 
    // Return if found, else continue to check in right 
    if (found != null) return found; 
} 

// Checks in right sub-tree if not found in left subtree 
if (searchNode.right != null) 
{ 
    // While checking in right sub-tree, then return irrespective of whether 
    // it was found or not found, since there aren't any more places to check 
    return (FindParent(BNode, searchNode.right)); 
} 
+0

return 호출을 제거하여 BNode returnNode로 돌아가서 null이 아닌지 확인한 후 반환합니다. 고마워, 고마워! –