从上到下打印出二叉树的每个节点,同一层的节点按照从左到右的顺序打印。
例如:
给定二叉树: [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,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-ii-lcof
此题实现层次遍历跟第一题一样,但是我么你需要思考怎么确定一层的数据。当一层扫描结束的时候,队列中存在的是下一层数据。
public static List> LevelOrder2(TreeNode root)
{
List> res = new List>();
if (root == null)
{
return res;
}
Queue queue = new Queue();
queue.Enqueue(root);
while (queue.Count > 0)
{
//Console.WriteLine("+++++++++++++++++++++++"+queue.Count);
int num = queue.Count;
List temp = new List();
for(int i = 1; i <= num; i++)
{
TreeNode node = queue.Dequeue();
temp.Add(node.data);
if (node.leftChild != null)
{
queue.Enqueue(node.leftChild);
}
if (node.rightChild != null)
{
queue.Enqueue(node.rightChild);
}
}
res.Add(temp);
}
// 使用foreach LINQ方法
//res.ForEach(num => num.ForEach(n => Console.Write(n+",")));//打印1,2,5,7,8,10,
Console.WriteLine("[");
foreach(List list1 in res)
{
Console.Write("[");
foreach(int i in list1)
{
Console.Write(i + " ");
}
Console.WriteLine("]");
}
Console.WriteLine("]");
return res;
}
使用一的数据,结果如下:
[
[3 ]
[9 20 ]
[15 7 ]
]
for(int i = 1; i <= queue.Count; i++)
最开始我的循环条件是这样,但是queue.Count是随着队列二变动的,不会是一层结束而变动