如何使用堆栈和深度优先搜索按顺序打印树?

时间:2014-11-30 10:51:09

标签: java depth-first-search

import java.util.LinkedList;
import java.util.Queue;

class Node {
public int iData; // data item (key)
public double dData; // data item
public Node leftChild; // this node's left child
public Node rightChild; // this node's right child
public int level;
public boolean flag;

public void displayNode() // display ourself
{
    System.out.print('{');
    System.out.print(level);
    System.out.print(", ");
    System.out.print(iData);
    System.out.print(", ");
    System.out.print(dData);
    System.out.print("} ");
    System.out.println(" ");
}
} // end class Node
// //////////////////////////////////////////////////////////////

class Tree {
private Node root; // first node of tree

// -------------------------------------------------------------
public Tree() // constructor
{
root = null;
} // no nodes in tree yet
// -------------------------------------------------------------

public void insert(int id, double dd) {
Node newNode = new Node(); // make new node
newNode.iData = id; // insert data
newNode.dData = dd;
if (root == null) // no node in root
    root = newNode;
else // root occupied
{
    Node current = root; // start at root
    Node parent;
    while (true) // (exits internally)
    {
        parent = current;
        if (id < current.iData) // go left?
        {
            current = current.leftChild;
            if (current == null) // if end of the line,
            { // insert on left
                parent.leftChild = newNode;
                return;
            }
        } // end if go left
        else // or go right?
        {
            current = current.rightChild;
            if (current == null) // if end of the line
            { // insert on right
                parent.rightChild = newNode;
                return;
            }
        } // end else go right
    } // end while
} // end else not root
} // end insert()
// -------------------------------------------------------------

public void breadthFirstDisplay() {
    Queue newQueue = new LinkedList();
    int level = 0;
    newQueue.add(root);
    int temp = root.iData;
    while (!newQueue.isEmpty()) {
        Node theNode = (Node) newQueue.remove();
        if (temp > theNode.iData)
            level++;
        theNode.level = level;
        theNode.displayNode();
        temp = theNode.iData;
        if (theNode.leftChild != null) {
            newQueue.add(theNode.leftChild);
        }
        if (theNode.rightChild != null) {
            newQueue.add(theNode.rightChild);
        }
    }
}

public void depthFirstStackDisplay() {

}
// -------------------------------------------------------------
} // end class Tree
// //////////////////////////////////////////////////////////////

class TreeApp {
public static void main(String[] args){
Tree theTree = new Tree();

theTree.insert(5, 1.5);
theTree.insert(4, 1.2);
theTree.insert(6, 1.7);
theTree.insert(9, 1.5);
theTree.insert(1, 1.2);
theTree.insert(2, 1.7);
theTree.insert(3, 1.5);
theTree.insert(7, 1.2);
theTree.insert(8, 1.7);

theTree.breadthFirstDisplay();
theTree.depthFirstStackDisplay();

}// -------------------------------------------------------------
} // end class TreeApp
// //////////////////////////////////////////////////////////////

我想通过深度优先搜索来编写函数 这样输出就是1,2,3,4,5,6,7,8,9

布尔标志在类Node中设置,我希望该函数类似于广度优先搜索。

我无法找到相关来源来帮助我完成它。

1 个答案:

答案 0 :(得分:0)

你可以尝试这个alogo打印深度优先遍历(根据你的问题顺序遍历)。它将使用堆栈。

1)创建一个空堆栈。

2)以root身份初始化当前节点

3)将当前节点推送到S并将current = current-&gt; left设置为left,直到current为NULL

4)如果current为NULL并且堆栈不为空,那么

 a) Pop the top item from stack.

 b) Print the popped item, set current = popped_item->right 

 c) Go to step 3.

5)如果current为NULL并且堆栈为空,那么我们就完成了。

我对Java知之甚少,但你可以借助这个c代码:

    /* Iterative function for inorder tree traversal */
void inOrder(struct Node *root)
{
  /* set current to root of binary tree */
  struct Node *current = root;
  struct sNode *s = NULL;  /* Initialize stack s */
  bool done = 0;

  while (!done)
  {
    /* Reach the left most Node of the current Node */
    if(current !=  NULL)
    {
      /* place pointer to a tree node on the stack before traversing
        the node's left subtree */
      push(&s, current);                                              
      current = current->leftChild; 
    }

    /* backtrack from the empty subtree and visit the Node
       at the top of the stack; however, if the stack is empty,
      you are done */
    else                                                             
    {
      if (!isEmpty(s))
      {
        current = pop(&s);
        printf("%d ", current->idata);

        /* we have visited the node and its left subtree.
          Now, it's right subtree's turn */
        current = current->rightChild;
      }
      else
        done = 1;
    }
  } /* end of while */ 
}