Sword refers to Offer-57-print the binary tree into multiple lines

Title description

The binary tree is printed layer by layer from top to bottom, and the nodes of the same layer are output from left to right. Output one line per layer

Idea analysis

This question is similar to the previous Z-shaped printing binary tree . But there are also different places. For the problem of zigzag printing, he will use the stack interchangeably, so there is no need to consider the order of storage in this layer and the next layer. Here, a queue is used to traverse a level according to the characteristics of first-in first-out.

Code

import java.util.ArrayList;
import java.util.Queue;
import java.util.LinkedList;
/*
public class TreeNode {
    int val = 0;
    TreeNode left = null;
    TreeNode right = null;

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

    }

}
*/
public class Solution {
    
    
    ArrayList<ArrayList<Integer> > Print(TreeNode pRoot) {
    
    
    ArrayList<ArrayList<Integer>> result = new ArrayList<>();
        if(pRoot==null){
    
    
            return result;
        }
    ArrayList<Integer> singlePath = new ArrayList<>();
   Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(pRoot);
        int count = 0;//用于记录又多少个节点的值已经被取出来
        int num = 1;//用于记录每层加入队列的数
        while(!queue.isEmpty()){
    
    
            TreeNode temp = queue.poll();
            singlePath.add(temp.val);
            count++;
            if(temp.left!=null){
    
    
                queue.offer(temp.left);
            }
            if(temp.right!=null){
    
    
                queue.offer(temp.right);
            }
            if(count == num){
    
    
                count = 0;//重新开始计数
                num = queue.size();//将本层的个数赋予num
                result.add(singlePath);
                singlePath = new ArrayList<>();
            }
        }
        return result;
    }
}

Guess you like

Origin blog.csdn.net/H1517043456/article/details/107592353