从上到下打印出二叉树的每个节点,同一层的节点按照从左到右的顺序打印。
例如:
给定二叉树: [3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
返回:
[3,9,20,15,7]
来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/cong-shang-dao-xia-da-yin-er-cha-shu-lcof
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;namespace SuanfapRractice
{public class TreeNode{public int data;public TreeNode leftChild;public TreeNode rightChild;public TreeNode(int data){this.data = data;}}
}
这是二叉树的构造类
我们需要构建具体的二叉树,从根开始root,然后分别将节点连接。
在遍历二叉树的时候,从本题我们可以知道我们使用的是层遍历,层遍历需要借助一个队列,去记录下一层的节点。
using System.Collections;
using System.Collections.Generic;
using System.Numerics;
using System.Reflection.Metadata.Ecma335;
using System.Runtime.InteropServices;
using System.Security.Cryptography;
using System;
using System.Collections.Generic;
using System.Xml.Linq;
using SuanfapRractice;
using System.Linq;public class Solution
{public static void Main(String[] args){TreeNode root = new TreeNode(3);root.leftChild = new TreeNode(9);root.rightChild = new TreeNode(20);root.rightChild.leftChild = new TreeNode(15);root.rightChild.rightChild = new TreeNode(7);LevelOrder(root);}public static int[] LevelOrder(TreeNode root){if (root == null){return new int[0];}Queue queue = new Queue();queue.Enqueue(root);List res = new List();while (queue.Count > 0){TreeNode node = queue.Dequeue();res.Add(node.data);if (node.leftChild != null){queue.Enqueue(node.leftChild);}if (node.rightChild != null){queue.Enqueue(node.rightChild);}}// 使用foreach LINQ方法res.ForEach(num => Console.WriteLine(num + ", "));//打印return res.ToArray();}
结果为
3,9,20,15,7,
入队 Enqueue,出队 Dequeue
Queue q = new Queue();
q.Enqueue('A');
ch = (char)q.Dequeue();
上一篇:唐山3案例入选省级!另外,限价商品住房登记中! 限价商品房唐山 唐山限价商品房申请条件
下一篇:中国银行获得发明专利授权:“基于Nodejs的移动APP安装包管理系统及方法” 涓浗閾惰鍙栧緱浣╂埓瑁呯疆涓撳埄 涓浗閾惰鑾峰緱鍙戞槑涓撳埄鎺堟潈