剑指offer---从上往下打印二叉树

吐槽

和数据结构相关的题还是有点生疏,看来还是要抽点时间把数据结构的书再复习一遍

题目描述

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

思路

这道题实际上就是二叉树的层序遍历,把题干抽象出来就是队列的问题,先让根节点入队,打印值,再让根节点的左子树、右子树依次入队,打印值,直到将树遍历完为止。

代码

import java.util.ArrayList; 		//必须记得写头文件,不然牛客网的编译不能通过
import java.util.LinkedList;
import java.util.Queue;

public class leetcode_22 {
    public static void main(String[] args) {

    }
     public class TreeNode {
     int val = 0;
     TreeNode left = null;
     TreeNode right = null;

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

     }

     public ArrayList<Integer> PrintFromTopToBottom(TreeNode root) {
         Queue<TreeNode> queue = new LinkedList<>();		//队列,存结点,注意Queue是一个接口
         ArrayList<Integer> result = new ArrayList<>();		//动态数组存值
         if (root == null){
             return result;
         }

         queue.offer(root);		//根节点插入队列中

         while (!queue.isEmpty()){		//直到根节点所有元素出队为止
             TreeNode tmpNode = queue.poll();		//出队操作
             result.add(tmpNode.val);
             if (tmpNode.left != null){		//结点的左子树入队
                 queue.offer(tmpNode.left);
             }
             if (tmpNode.right != null){	//结点的右子树入队
                 queue.offer(tmpNode.right);
             }
         }
         return result;
      }

 }


}

你可能感兴趣的:(算法)