7.2 2叉树广度优先经典代码(C#)

 

2叉树

public class TreeNode
{
    public int val;
    public TreeNode left;
    public TreeNode right;

    public TreeNode(int x)
    {
        val = x;
    }
}

 

2叉树广度优先经典代码

public List<int> bfs(TreeNode root) {
        Queue<TreeNode> queue = new Queue<TreeNode>();
        if (root!=null)
        {
            queue.Enqueue(root);
        }
        List<int> result = new List<int>();
        while (queue.Count>0) {
            TreeNode node = queue.Dequeue();
            result.Add(node.val);
            if (node.left!=null)
            {
                queue.Enqueue(node.left);
            }
            if (node.right!=null)
            {
                queue.Enqueue(node.right);
            }
        }
        return result;
    }

 

posted @ 2022-10-13 18:24  盛沧海  阅读(27)  评论(0编辑  收藏  举报