zoukankan      html  css  js  c++  java
  • 从上往下打印二叉树

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

    实现语言:Java

    import java.util.ArrayList;
    import java.util.LinkedList;
    /**
    public 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) {
            LinkedList<TreeNode> que=new LinkedList<TreeNode>();
            ArrayList<Integer> res=new ArrayList<Integer>();
            if(root==null){
                return res;
            }
            que.offer(root);
            while(!que.isEmpty()){
                root=que.poll();
                res.add(root.val);
                if(root.left!=null){
                    que.offer(root.left);
                }
                if(root.right!=null){
                    que.offer(root.right);
                }
            }
            return res;
        }
    }
    
  • 相关阅读:
    PHP
    PHP
    PHP
    PHP
    PHP
    MySQL
    PHP
    PHP
    PHP
    linux 用户及用户组管理
  • 原文地址:https://www.cnblogs.com/xidian2014/p/10197572.html
Copyright © 2011-2022 走看看