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; }
*****有道无术,术尚可求;有术无道,止于术。*****