美文网首页
二叉树的层序遍历

二叉树的层序遍历

作者: 霍运浩 | 来源:发表于2019-04-21 18:38 被阅读0次

题目描述

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

解题思路

思路是用queue模拟一个队列来存储相应的TreeNode

代码实现

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.Queue;
 class TreeNode {
    int val = 0;
    TreeNode left = null;
    TreeNode right = null;

    public TreeNode(int val) {
        this.val = val;

    }

}

public class Solution {
    public ArrayList<Integer> PrintFromTopToBottom(TreeNode root) {
       
        if(root==null){
            return null;
        }
       Queue queue=new LinkedList();
       queue.add(root);
       while(!queue.isEmpty()){
           root=(TreeNode) queue.poll();
           System.out.println(root.val);
           if(root.left!=null){
               queue.add(root);
           }
           if(root.right!=null){
               queue.add(root);
               
           }
       }
          return null;
        
    }

相关文章

网友评论

      本文标题:二叉树的层序遍历

      本文链接:https://www.haomeiwen.com/subject/mwbjgqtx.html