题目描述
从上到下按层打印二叉树,同一层结点从左至右输出。每一层输出一行。
解题思路—使用ArrayList层次遍历:这题就是剑指Offer—按之字形顺序打印二叉树的简化版。比较基础的就是用ArrayList、Stack或者Queue进行层次遍历。使用size记录每一层的结点个数,依次分层输出。
✨解题思路—递归:使用了DFS,深度遍历思想,深度+1,则结果中就多一行ArrayList,然后递归每个结点的左右子结点,在对应的深度层中加入val值。代码很简洁!推荐!
Java解题—使用ArrayList层次遍历
import java.util.ArrayList;
public class Solution {
ArrayList<ArrayList<Integer> > Print(TreeNode pRoot) {
ArrayList<ArrayList<Integer>> result = new ArrayList<>();
if(pRoot==null) return result;
ArrayList<TreeNode> node = new ArrayList<>();
node.add(pRoot);
while(!node.isEmpty()){
int size = node.size();
ArrayList<Integer> list = new ArrayList<>();
while(--size>=0){
TreeNode pnode = node.get(0);
list.add(pnode.val);
if(pnode.left!=null) node.add(pnode.left);
if(pnode.right!=null) node.add(pnode.right);
node.remove(0);
}
result.add(list);
}
return result;
}
}
Java解题—递归
import java.util.ArrayList;
public class Solution {
ArrayList<ArrayList<Integer> > Print(TreeNode pRoot) {
ArrayList<ArrayList<Integer>> result = new ArrayList<>();
depth(pRoot, 1, result);
return result;
}
public void depth(TreeNode pRoot, int depth, ArrayList<ArrayList<Integer>> result){
if(pRoot==null) return;
if(depth>result.size())
result.add(new ArrayList<Integer>()); // 用来存储新一层深度
result.get(depth-1).add(pRoot.val); // 在对应的深度层中加入值
depth(pRoot.left, depth+1, result);
depth(pRoot.right, depth+1, result);
}
}