算法:二叉树

一 从上到下打印二叉树

1.1 题目描述

从上到下打印出二叉树的每个节点,同一层的节点按照从左到右的顺序打印。

例如:
给定二叉树: [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
 

1.2 思路以及代码

1.2.1 构建二叉树

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;}}
}

这是二叉树的构造类

1.2.2 题解以及代码

我们需要构建具体的二叉树,从根开始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,

1.2.3 c#需要注意的点

入队   Enqueue,出队 Dequeue

Queue q = new Queue();
q.Enqueue('A');
ch = (char)q.Dequeue();