-
Warm tip: if you don't understand the code, you may as well take out the paper and pen, find some examples, and walk through the program several times,
Search for related blogs, and then you will get a deeper understanding.
Title:
The binary tree is printed from top to bottom, and the nodes of the same layer are output from left to right. Output one line per layer.
Code idea:
Sequence traversal of binary tree is realized by queue. We need two variables: a start to record the number of nodes that have been printed in the current layer, an end to record the number of all nodes in the layer before, and a start == end to start the next layer after traversing the current layer in the table.
Solution 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> > res = new ArrayList<ArrayList<Integer> >(); if(pRoot == null) return res; ArrayList<Integer> temp = new ArrayList<Integer>(); Queue<TreeNode> layer = new LinkedList<TreeNode>(); layer.offer(pRoot); int start = 0, end = 1; while(!layer.isEmpty()){ TreeNode node = layer.poll(); temp.add(node.val); start ++; if(node.left != null) layer.add(node.left); if(node.right != null) layer.add(node.right); if(start == end){ start = 0; res.add(temp); temp = new ArrayList<Integer>(); end = layer.size(); } } return res; } }
Reference article:
https://www.weiweiblog.cn/print/