2012-05-10 3 views
2

자바에서 재귀 함수를 작성하려고하는 중이며 알파벳 순서로 단어로 가득 찬 arraylist를 취하고 최선을 다해 트리를 채 웁니다. 내가 알 수있는 한, 문제는 자바가 참조로 전달하지 않는다는 것입니다. 그래서 재귀 함수에서 트리의 왼쪽 상단과 오른쪽 지점이 가리키는 곳을 실제로 업데이트하지 않습니다. 트리의 맨 위가 아무 것도 가리 키지 않습니다. 이 작업을 수행하는 더 좋은 방법이 있습니까? 처음에 나무를 채우려는 나의 시도에서 그 표를 완전히 놓치고 있습니까?Java에서 재귀 함수를 사용하여 사전에 이진 트리를 채우기 위해

public void saveNode(BinaryTreeNode parent, int left, int right) 
{ 
    int middle = (int) Math.ceil(((double)(right-left))/2.0); 
    int curIndex; 
    curIndex = middle+left; 

    parent = new BinaryTreeNode(words.get(curIndex)); 

    if(middle != 1) 
    { 
     saveNode(parent.left, left, curIndex); 
     saveNode(parent.right, curIndex, right); 
    } 
} 

PS : 나는

답변

1

귀하의 문제가 자바에 비교적 새로운 해요 당신이 실행할 때

parent에 값을 할당 하지을 수행
parent = new BinaryTreeNode(words.get(curIndex)); 

까지 호출자가 그대로 걱정할 필요가 없으므로 호출 스택 위로 전파되지 않습니다.

public static void main(String[] args) { 
    // keep a reference to the root node so you can access the tree after loading 
    BinaryTreeNode root = new BinaryTreeNode(); 
    // pass the root node into the first call to the recursive method 
    saveNode(root, left, right); 
} 

public void saveNode(BinaryTreeNode parent, int left, int right) { 
    // keep building your tree as you descend into it 
    parent.left = new BinaryTreeNode(); 
    parent.right = new BinaryTreeNode(); 
    // pass the (new) branches into deeper calls  
    saveNode(parent.left, left, curIndex); 
    saveNode(parent.right, curIndex, right); 
} 
:이 같은 모양을 원하는 코드를

는 (문제와 관련이없는 코드를 복용)
관련 문제