1、层序遍历
public class Solution {
ArrayList<Integer> list = new ArrayList<>();
ArrayList<TreeNode> nodes = new ArrayList<>();
public ArrayList<Integer> PrintFromTopToBottom(TreeNode root) {
if(root !=null){
nodes.add(root);
while(nodes.size() !=0){
TreeNode n = nodes.remove(0);//删除并返回头结点
list.add(n.val);
if(n.left!=null){
nodes.add(n.left);
}
if(n.right!=null){
nodes.add(n.right);
}
}
}
return list;
}
}
2、前序遍历
public class Solution {
ArrayList<Integer> list = new ArrayList<>();
public ArrayList<Integer> PrintFromTopToBottom(TreeNode root) {
if(root !=null){
list.add(root.val); //根
PrintFromTopToBottom(root.left); //左
PrintFromTopToBottom(root.right); //右
}
retrun list;
}