二分查找树遍历显示节点最多N级
Binary searchTree traversal display nodes up to N level
我想显示最多 3 级的节点。在这里,我正在使用级别顺序 (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);
}
}
}
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; }
}
我想显示最多 3 级的节点。在这里,我正在使用级别顺序 (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);
}
}
}
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; }
}