1、题目描述
从上往下打印出二叉树的每个节点,同层节点从左至右打印。
2、解法( 时间复杂度O(n) )
public class Solution {
public ArrayList<Integer> PrintFromTopToBottom(TreeNode root) {
ArrayList<Integer> result = new ArrayList<>();
if(root == null) return result;
Queue<TreeNode> queue = new LinkedList<>();
queue.offer(root);
while(!queue.isEmpty()){
TreeNode tmp = queue.poll();
result.add(tmp.val);
if(tmp.left != null) queue.offer(tmp.left);
if(tmp.right != null) queue.offer(tmp.right);
}
return result;
}
}
3、总结
1、栈和队列都可以使用LinkedList链表来实现,因为是双向链表,而且它插入和删除的效率高。
参考链接:
https://www.cnblogs.com/yueyanglou/p/5231901.html