剑指offer-从上往下打印二叉树
剑指offer-从上往下打印二叉树
剑指offer-从上往下打印二叉树
Description
从上往下打印出二叉树的每个节点,同层节点从左至右打印。
Solution
import java.util.ArrayList;
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 {
public ArrayList<Integer> PrintFromTopToBottom(TreeNode root) {
ArrayList<Integer> list = new ArrayList<>();
LinkedList<TreeNode> link = new LinkedList<>();
if(root==null){
return list;
}
link.add(root);
while(!link.isEmpty()){
TreeNode temp = link.remove();
list.add(temp.val);
if(temp.left!=null){
link.add(temp.left);
}
if(temp.right!=null){
link.add(temp.right);
}
}
return list;
}
}
Discuss
思路是用LinkedList模拟一个队列来存储相应的TreeNode