算法:二叉树
admin
2024-04-28 01:17:38
0

一 从上到下打印二叉树

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();

相关内容

热门资讯

港股迎来马年首个交易日,AI与... 2月20日,港股迎来马年首个交易日。截至收盘,恒生指数报26643.69,跌0.98%,恒生科技指数...
日本的海外资本会“大规模回流”... 1月份日债收益率飙升,吸引海外资金流入。据日本证券交易协会数据,1月日债净购买额达6.04万亿日元,...
品美食赏非遗过大年 沉浸式文旅... 这个春节,多种非遗活动在全国多地上演。品美食,赏非遗,逛民俗文化展演,各地群众在浓浓年味中,沉浸式感...
智谱 、MINIMAX市值突破... 2月20日,港股开盘后,大模型公司智谱和MINIMAX股价均大幅上涨,创上市以来新高。截至记者发稿,...
Z世代购物车|“90分钟卖了1... 中新经纬2月20日电 (林琬斯)北京的小柏(化名)喜欢闻香,家里摆满了香水、香囊、香薰、线香。此前工...
舞龙狮、打铁花、花车巡游 四川... 封面新闻记者 周翼 徐湘东 从2月17日至2月19日,四川攀枝花市米易县连续举办“中国年味·米易最浓...
张艺谋谈“间谍在垃圾桶交接手机... 念一 据长安街知事微信公号消息,2月18日,在《惊蛰无声》首映会上,有观众问及“间谍在垃圾桶交接手机...
亚马逊超越沃尔玛,成全球营收最... 2026.02.20本文字数:839,阅读时长大约2分钟来源 |中国经济网综合上海证券报、央视财经等...
春晚机器人出圈背后,“零失误”... 看上去“零失误”的春晚机器人,它走进现实的真正难题不在舞台和工厂,而在于如何先走进千家万户了解需求,...
美联储官员发出警告:AI如果继... 美联储理事迈克尔·S·巴尔(Michael S. Barr)周二就人工智能的潜在发展轨迹发出了严重警...