2013-10-15 1 views
2

특정 수준의 이진 트리 인쇄 방법을 알고 싶습니다. BFS에 관한 많은 질문을 읽었지만 printin에 대해서는 단 한 수준도 발견되지 않았습니다.이진 트리, 한 수준 (BFS) 만 인쇄하십시오.

6 
/\ 
4 8 
/\/\ 
1 5 7 9 

LEVE이 1, 5, 7 것, 9. 감사 : 나는 인쇄 할 공통의 ​​BFS 검색을 변경하는 방법을

, 말을이 나무의 레벨 2를 할 수 있습니다!

+0

현재 사용중인 레벨을 추적하고 2로 끝나면 종료합니다. –

+0

꽤 명확하지만 일반 BFS를 사용하여이를 수행하는 방법을 찾을 수 없습니다. 노드가있는 대기열을 처리하지만 ' T는 수준을 구별합니다. 그냥 대기열에 넣고 BFS 순서로 처리합니다. 모든 수준의 노드 양을 확인하는 이상한 솔루션이 있지만 그럴 때가 무너집니다 non-full tree를 생각해 보자. – nitrnitr

+0

한 가지 방법은 {node}가 아닌 {level, node}의 튜플을 큐에 넣는 것이다. –

답변

0

좋아. 이진 검색 트리에서

는 일정 수준 (GenericTree 및 GenericQueue은 물론 특정 클래스입니다 가장 낮은 번호를 찾을 또한 내가 전체 운동 그래서 몇 가지 이상한 여부 들릴 수 traslated :. P

public int calculateMinimum(BinaryTree<Integer> tree, int n){ 
    GenericQueue<BinaryTree<Integer>> queue = new GenericQueue<BinaryTree<Integer>>(); 
    queue.push(tree); 
    queue.push(new BinaryTree<Integer>(-1)); 
    int nActual = 0; //actual level 
    while (!queue.isEmpty()){ 
     tree = queue.pop(); 
     if (nActual == n){ 
      int min = tree.getRootData(); 
      while (!queue.isEmpty()){ 
       tree = queue.pop(); 
       if (!tree.getRootData().equals(-1) && (tree.getRootData()<min)) 
        min = tre.getRootData(); 
      } 
      return min; 
     } 
     if (!tree.getLeftChild().getRootData() == null)) 
      queue.push(tree.getLeftChild()); 
     if (!tree.getRightChild().getRootData() == null)) 
      queue.push(tree.getRightChild()); 
     if ((tree.getRootData().equals(-1) && (!queue.isEmpty())){ 
      nActual++; 
      queue.push(new BinaryTree<Integer>(-1)); 
     } 
    } 
    return -1; 
}     
1

노드에 레벨 속성이 있어야합니다. 여기

if (level == 2) //or whatever level you wish 
{ 
    ... 
} 

이 좋은 예이다 : 당신이 나무에 통과 할 때 그리고, 당신이 물어 노드에는 레벨이 존재하지 않는 경우 Find all nodes in a binary tree on a specific level (Interview Query)

당신이 그것을 변경할 수 없습니다, 당신은 할 수 있습니다 메서드에서 전역 변수로 사용하여 검사하는 것이 바람직하지 않지만 또 하나의 솔루션입니다. 코드에서이 대답을 확인하지는 못했지만 해결책에 매우 가깝다고 생각합니다.

예컨대 : 내가 유사한 문제에 대한 교수의 대답을 얻었다

int level = 0; 

    public void PrintOneLevelBFS(int levelToPrint)  
    {  
     Queue q = new Queue(); 
     q.Enqueue(root); //Get the root of the tree to the queue. 

     while (q.count > 0) 
     { 
      level++; //Each iteration goes deeper - maybe the wrong place to add it (but somewhere where the BFS goes left or right - then add one level). 
      Node node = q.DeQueue(); 

      if (level == levelToPrint) 
      { 
       ConsoleWriteLine(node.Value) //Only write the value when you dequeue it 
      } 

      if (node.left !=null) 
      { 
       q.EnQueue(node.left); //enqueue the left child 
      } 
      if (n.right !=null) 
      { 
       q.EnQueue(node.right); //enqueue the right child 
      } 
     } 
    } 
+0

Misha, 좋은 해결책입니다.하지만 노드에서이 속성을 사용할 수 없다면 어떻게 될까요? 저는 컴퓨터 과학 대학에 다니고 있으며 이것이 가능한 시험 연습 일 수 있다고 생각합니다. – nitrnitr

+0

@Pphax 나는 대답을 편집했다. - 그것을 확인해라 :) –

+0

음, 나는 그것이 작동 할 것이라고 생각하지 않는다. 루프가 돌아갈 때마다 레벨이 증가 할 것이다 (각 루프마다 1 루프 = 1 노드, 그 다음에는 각 레벨이 아니다). – nitrnitr