22. Print the binary tree from top to bottom

Topic description

       Each node of the binary tree is printed from top to bottom, and the nodes of the same layer are printed from left to right; ps. is the level traversal

Problem solving ideas

       Use a queue (LinkedList) for hierarchical traversal;

     public ArrayList<Integer> PrintFromTopToBottom(TreeNode root) {
        ArrayList<Integer> list = new ArrayList<Integer>();
        if (root == null) {
            return list; //If the root node is empty, return an empty List directly
        }

        LinkedList<TreeNode> queue = new LinkedList<TreeNode>();  //队列
        queue.add(root); //Add root node
        
        while (!queue.isEmpty()){
            TreeNode current = queue.pop();
            list.add(current.val);

            if (current.left != null){   
                queue.add(current.left); //Add the left node to the queue
            }
            if (current.right != null){
                queue.add(current.right); //Add the right node to the queue
            }
        }
        return list;
    }

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324687841&siteId=291194637