剑指offer--算法题--24--从上向下打印二叉树

直接上代码

package JvavaDataTest;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.Queue;

public class Solution {
    /**
     *       1
     *      2 3
     *    4 5 6 7
     */
    public static void main(String[] args) {
        TreeNode tn1 = new TreeNode(1);
        TreeNode tn2 = new TreeNode(2);
        TreeNode tn3 = new TreeNode(3);
        TreeNode tn4 = new TreeNode(4);
        TreeNode tn5 = new TreeNode(5);
        TreeNode tn6 = new TreeNode(6);
        TreeNode tn7 = new TreeNode(7);
        tn1.left = tn2;
        tn1.right = tn3;

        tn2.left = tn4;
        tn2.right = tn5;

        tn3.left = tn6;
        tn3.right = tn7;

        Solution sl = new Solution();
        ArrayList<Integer> list = sl.PrintFromTopBottom(tn1);
        sl.printArryList(list);
    }
    public ArrayList<Integer> PrintFromTopBottom(TreeNode root){
        ArrayList<Integer> result = new ArrayList<Integer>();
        if(root == null){
            return result;
        }
        //先创建一个队列
        Queue<TreeNode> q = new LinkedList<TreeNode>();
        //将根节点加入队列
        q.add(root);
        result.add(root.val);
        //判断根节点是否为空,不为空的话 出队,然后加入集合
        //再把left加入 继续判断
        //再把right加入 继续判断
        while(!q.isEmpty()){
            TreeNode tmp = q.poll();
            if(tmp.left != null){
                q.add(tmp.left);
                result.add(tmp.left.val);
            }
            if(tmp.right != null){
                q.add(tmp.right);
                result.add(tmp.right.val);
            }
        }
        return result;
    }

    public void printArryList(ArrayList<Integer> list){
        for(Integer it:list){
            System.out.println(it);
        }
    }
}
class TreeNode{
    int val = 0;
    TreeNode left = null;
    TreeNode right = null;

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

直接上结果

猜你喜欢

转载自blog.csdn.net/lsm18829224913/article/details/81176797