二进制搜索树遍历显示节点最多N级

时间:2015-04-15 21:01:27

标签: c#-3.0 binary-search-tree

我想显示最多3级的节点。这里我使用Level order(BFS)编写代码。每个节点有2个孩子。我不确定如何在显示该级别数据后增加级别并希望显示最多3级。

public Void LevelOrder()    
{      
 Queue q = new Queue();
int level=1;
 q.Enqueue(root);
 while (!q.empty() && level<=3)
 {
   level++;
    Node n = q.DeQueue();
    Console.Writeln(n.Value); 
    if (n.left !=null)
    {
        q.EnQueue(n.left);
    }
    if (n.right !=null)
    {
       q.EnQueue(n.right);
    }
 }
}

1 个答案:

答案 0 :(得分:1)

private static void Main(string[] args)
        {
            var root = new Node
            {
                Val = 0,
                Left = new Node {Val = 1, Left = new Node {Val = 2, Left = new Node() {Val = 3}}},
                Right = new Node() {Val = 1, Right = new Node() {Val = 2, Right = new Node() {Val = 3,Left = new Node(){Val = 4}}}}
            };
            Printbylevel(root, 5);
            Console.ReadLine();
        }

        public static void Printbylevel(Node root, int depth)
        {
            Stack<Node> activenodes = new Stack<Node>();
            Stack<Node> nextnodes = new Stack<Node>();
            activenodes.Push(root);
            var level = 0;
            while (activenodes.Any())
            {
                level++;
                if (level == depth+1) return;
                Console.WriteLine("\n----{0}----", level);
                while (activenodes.Any())
                {
                    var current = activenodes.Pop();
                    if (current == null) continue;
                    Console.Write(current.Val);
                    nextnodes.Push(current.Left);
                    nextnodes.Push(current.Right);
                }
                while (nextnodes.Any())
                {
                    activenodes.Push(nextnodes.Pop());
                }
            }
        }
    }

    internal class Node
    {
        public int Val;
        public Node Right { get; set; }
        public Node Left { get; set; }
    }