• 从上往下打印出二叉树的每个节点,同层节点从左至右打印。


     1 /*
     2 思路:借助栈来实现  
     3 树为空时  返回空
     4 树不为空  将根节点如队列
     5 然后将队列首元素出队列   如果该元素有左子节点那么左子节点入队了  如果该元素有右子节点那么右子节点入队列
     6 最后  进队列的顺序也就是出队列的顺序
     7 */
     8 import java.util.ArrayList;
     9 import java.util.*;
    10 import java.util.Iterator;
    11 /**
    12 public class TreeNode {
    13     int val = 0;
    14     TreeNode left = null;
    15     TreeNode right = null;
    16 
    17     public TreeNode(int val) {
    18         this.val = val;
    19 
    20     }
    21 
    22 }
    23 */
    24 public class Solution {
    25     public ArrayList<Integer> PrintFromTopToBottom(TreeNode root) {      
    26         Queue <TreeNode>queue=new LinkedList<TreeNode>();
    27         ArrayList <Integer>list=new ArrayList<Integer>();
    28          if(root==null)return list;
    29         queue.offer(root);
    30         while(!queue.isEmpty()){
    31              TreeNode t=queue.poll();
    32              list.add(t.val);
    33             if(t.left!=null){
    34                 queue.offer(t.left);
    35             }
    36             if(t.right!=null){
    37                 queue.offer(t.right);
    38             }
    39         }
    40         return list;
    41                                
    42     }
    43 }
  • 相关阅读:
    Python和C#基本算法实现对比
    数据库并发
    NetCore 启动地址配置详解
    SkyWalking Liunx 环境搭建&NetCore接入
    Autofac踩坑经历
    centos 7 安装elasticsearch
    centos 7 java1.8安装
    AppDomin学习与分享
    .Net 程序代码混淆加密工具 ILProtector
    c# 重新认识 Double 浮点型
  • 原文地址:https://www.cnblogs.com/bolianggufeng/p/8541801.html
Copyright © 2020-2023  润新知