從上到下按層列印二叉樹,同一層結點從左至右輸出。每一層輸出一行
阿新 • • 發佈:2020-07-26
思路:遞迴,擴容
增加一個deep引數,內部list數量與deep相同,每個深度對應一個list
根節點新增到list(deep-1),然後分別對其左右子樹遞迴求每層的節點,深度每到一個孩子+1
import java.util.ArrayList; /* public class TreeNode { int val = 0; TreeNode left = null; TreeNode right = null; public TreeNode(int val) { this.val = val; } } */ public classSolution { ArrayList<ArrayList<Integer> > Print(TreeNode pRoot) { ArrayList<ArrayList<Integer>> list=new ArrayList<>(); depth(pRoot,1,list); return list; } public void depth(TreeNode root,int deep,ArrayList<ArrayList<Integer>> list){if(root==null){ return; } if(deep>list.size()){ list.add(new ArrayList<>()); } list.get(deep-1).add(root.val); depth(root.left,deep+1,list); depth(root.right,deep+1,list); } }