📜  二叉树级别遍历 - C# 代码示例

📅  最后修改于: 2022-03-11 14:49:12.190000             🧑  作者: Mango

代码示例1
public static void levelOrderTraversal(Node root)
    {
        // base case
        if (root == null) {
            return;
        }
 
        // create an empty queue and enqueue the root node
        Queue queue = new ArrayDeque<>();
        queue.add(root);
 
        // to store the current node
        Node curr;
 
        // loop till queue is empty
        while (!queue.isEmpty())
        {
            // process each node in the queue and enqueue their
            // non-empty left and right child
            curr = queue.poll();
 
            System.out.print(curr.key + " ");
 
            if (curr.left != null) {
                queue.add(curr.left);
            }
 
            if (curr.right != null) {
                queue.add(curr.right);
            }
        }
    }