2013-10-11 9 views
0

중위 방법으로 이진 트리에서 노드를 찾아 반환하고 그것을 PS를 반환 : 이진 트리가 같은 값을 갖는 두 개의 노드를 포함 할 수있다. 은 예약 주문 방식으로중위 방법으로 이진 트리에서 주어진 값을 가진 노드를 찾아 그것을

노드 찾기 (노드 루트, INT의 발) {...}

사람이 솔루션을 공유 할 수 있습니다 그것을 쉽게?

+0

는 어디 붙어 있습니까? – smk

+0

@smk 나는 그것을 반복적으로 풀려고했는데, 일단 노드를 찾아서 멈추는 방법을 찾으면 ? – Nathan

답변

2

Havent는 철저히 테스트했지만이 코드가 작동합니다.

public TreeNode find(TreeNode cur,int val) { 

     TreeNode result = null; 
     if(cur.left != null) 
      result = find(cur.left,val); 


     if(cur.value == val) 
      return cur; 
     if(result ==null && cur.right != null) 
      result = find(cur.right,val); 

     return result; 

    } 
+0

조금 전에 고마워. cur.value == val 또한 result == null인지 확인해야한다. – Nathan

0
public static int treeSearch(Node head, int element){ 

     if(head.value==element) 
      return 1; 

     else { 
       if (head.left != null) 
       return inOrderSearch(head.left, element); 

       else if (head.right != null) 
       return treeSearch(head.right, element); 
     } 
    return 0; 
} 
관련 문제