算法:二叉树
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();

相关内容

热门资讯

WPK方法课程!约局吧德州有挂... WPK方法课程!约局吧德州有挂吗,WPKai多功能透视工具1、玩家可以在约局吧德州有挂吗线上大神俱乐...
正版辅助小猪对对碰辅助多功能A... 正版辅助小猪对对碰辅助多功能AI插件,小猪对对碰本来存在有辅助插件小猪对对碰破解侠是真的助透视。每个...
WPK工具方针!约局吧德州真的... WPK工具方针!约局吧德州真的存在透视吗,德州扑克ai多功能开挂app;运约局吧德州真的存在透视吗辅...
正版透视器一乐棋牌透视器多功能... 正版透视器一乐棋牌透视器多功能AI软件,一乐棋牌都是真的有透视器软件1、操作简单,无需一乐棋牌手机版...
WPK工具要领!德州机器人代打... WPK工具要领!德州机器人代打脚本,德扑之星ai多功能开挂工具1、德州机器人代打脚本模拟器是什么优化...
正版开挂葫芦岛爱玩麻将开挂多功... 正版开挂葫芦岛爱玩麻将开挂多功能AI技巧,葫芦岛爱玩麻将好像真的有开挂技巧1、游戏颠覆性的策略玩法,...
WPK方法操作!德州透视插件,... WPK方法操作!德州透视插件,智星菠萝德州ai多功能开挂教程1、德州透视插件破解器简单,德州透视插件...
正版开挂鹤岗麻将开挂多功能AI... 正版开挂鹤岗麻将开挂多功能AI攻略,鹤岗麻将一贯是真的有开挂攻略鹤岗麻将透视方法中分为三种模型:鹤岗...
WPK俱乐部秘籍!哈糖大菠萝万... WPK俱乐部秘籍!哈糖大菠萝万能挂,智星菠萝德州ai多功能辅助教程运哈糖大菠萝万能挂辅助工具,进入游...
正版辅助微乐齐齐哈尔麻将辅助多... 正版辅助微乐齐齐哈尔麻将辅助多功能AI插件,微乐齐齐哈尔麻将都是是真的有辅助插件1、微乐齐齐哈尔麻将...