当前位置:网站首页>Sword finger offer 23 - print binary tree from top to bottom

Sword finger offer 23 - print binary tree from top to bottom

2022-07-06 14:18:00 Snail Internet

Binary tree structure

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

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

Title Description

  • Print each node of the binary tree from top to bottom , The nodes of the same layer are printed from left to right .

analysis

  • Investigate sequence traversal
  • Every time I print a node , If the node has child nodes , Then put the child nodes of this node at the end of a queue .
  • Next, the head of the queue takes out the node that first entered the queue , Repeat the previous print operation , Until all nodes in the queue are printed .

Code implementation

public ArrayList<Integer> printFromTopToBottom(TreeNode root) {
    
    ArrayList<Integer> list = new ArrayList<Integer>();
    if(root==null){
    
        return list;
    }
    Queue<TreeNode> queue = new LinkedList<TreeNode>();
    queue.offer(root);
    while (!queue.isEmpty()) {
    
        TreeNode treeNode = queue.poll();
        if (treeNode.left != null) {
    
            queue.offer(treeNode.left);
        }
        if (treeNode.right != null) {
    
            queue.offer(treeNode.right);
        }
        list.add(treeNode.val);
    }
    return list;
}

Auxiliary package

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

原网站

版权声明
本文为[Snail Internet]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202131409320865.html