2014-09-06 129 views
0

我開始與堆棧的代碼:深度優先搜索無堆

void Foo(TreeNode root) 
    { 
     Stack nodes = new Stack(); 
     nodes.Push(root); 

     while (nodes.Count > 0) 
     { 
      TreeNode node = (TreeNode) nodes.Pop(); 
      Console.WriteLine(node.Text); 
      for (int i = node.Nodes.Count - 1; i >= 0; i--) 
       nodes.Push(node.Nodes[i]); 
     } 
    } 

但是,沒有棧我不知道,我應該做的。

我試過了。這是對的嗎 ? 任何人都可以建議我。

void Foo(TreeNode root) 
{ 
    if(root == null) return; 

    System.out.print(root.Value + "\t"); 
    root.state = State.Visited; 

    //for every child 
    for(Node n: root.getChild()) 
    { 
     //if childs state is not visited then recurse 
     if(n.state == State.Unvisited) 
     { 
      dfs(n); 
     } 
    } 
} 
+0

你有什麼具體問題?請參閱http://stackoverflow.com/help/how-to-ask和http://stackoverflow.com/help/mcve尋求幫助。 – jordanhill123 2014-09-06 01:41:01

+2

而且,請提醒一位老傢伙在這種情況下「DFS」的含義是什麼? – 2014-09-06 01:41:23

+1

是的,你剛剛發佈了一些Java代碼... – 2014-09-06 01:42:46

回答

0

使用:

Console.WriteLine(node.Text); 
for (Int i = 0; i < node.Nodes.Count; i++) 
    Foo(root.Nodes[i]); 
0
namespace ConsoleApplication3 
{ 
    using System.Collections.Generic; 

    public class Tree 
    { 
     public int Value { get; set; } 

     public List<Tree> TreeNode 
     { 
      get; 
      set; 
     } 
     public Tree() 
     { 
      this.TreeNode = new List<Tree>(); 
     } 
    } 

    public class Program 
    { 
     public static void Main() 
     { 
      Program pro = new Program(); 
      Tree tree = new Tree(); 
      tree.TreeNode.Add(new Tree() { Value = 1 }); 
      tree.TreeNode.Add(new Tree() { Value = 2 }); 
      tree.TreeNode.Add(new Tree() { Value = 3 }); 
      tree.TreeNode.Add(new Tree() { Value = 4 }); 
      pro.DepthFirstSearch(2, tree); 
     } 

     private Tree DepthFirstSearch(int searchValue, Tree root) 
     { 
      if (searchValue == root.Value) 
      { 
       return root; 
      } 

      Tree treeFound = null; 
      foreach (var tree in root.TreeNode) 
      { 
       treeFound = DepthFirstSearch(searchValue, tree); 
       if (treeFound != null) 
       { 
        break; 
       } 
      } 

      return treeFound; 

     } 
    } 
}