The sword refers to Offer-Java-printing binary tree from top to bottom

Print the binary tree from top to bottom


Question:
Print each node of the binary tree from top to bottom, and print the nodes at the same level from left to right.
Code:

package com.sjsq.test;

import java.util.ArrayList;
import java.util.Deque;
import java.util.LinkedList;

/**
 * @author shuijianshiqing
 * @date 2020/5/24 10:43
 */

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

public class Solution {
    
    

    public ArrayList<Integer> PrintFromTopToBottom(TreeNode root) {
    
    

        // 定义双向队列
        Deque<TreeNode> deque = new LinkedList<>();
        // 定义数组来存放结果
        ArrayList<Integer> result = new ArrayList<>();

        if(root == null){
    
    
            return result;
        }

        deque.add(root);

        while(!deque.isEmpty()){
    
    
            TreeNode node = deque.getFirst();
            deque.pollFirst();
            result.add(node.val);

            // 判断有没有左子树
            if(node.left != null){
    
    
                deque.addLast(node.left);
            }

            // 判断有没有右子树
            if(node.right != null){
    
    
                deque.addLast(node.right);
            }
        }

        return result;
    }
}

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=324116366&siteId=291194637