*Binary Tree Level Order Traversal
题目:
Given a binary tree, return the level order traversal of its nodes' values. (ie, from left to right, level by level).
For example:
Given binary tree {3,9,20,#,#,15,7}
,
3 / \ 9 20 / \ 15 7
return its level order traversal as:
[ [3], [9,20], [15,7] ]
题解:
这道题就是用传统的BFS来做。代码如下:
public class Solution { public List<List<Integer>> levelOrder(TreeNode root) { List<List<Integer>> res = new LinkedList<List<Integer>>(); Queue<TreeNode> queue = new LinkedList<TreeNode>(); if(root==null) return res; queue.add(root); while(!queue.isEmpty()) { int levelnum = queue.size(); //这层有几个TreeNode List<Integer> sublist = new LinkedList<Integer>(); for(int i=0; i<levelnum;i++) { TreeNode node = queue.poll(); if(node.left!=null) queue.add(node.left); if(node.right!=null) queue.add(node.right); sublist.add(node.val); } res.add(sublist); } return res; } }
注意:
广度优先算法:用queue,先进先出。
入queue用add:Appends the specified element to the end of this list. This method is equivalent to addLast(E)
.
出queue用poll:Retrieves and removes the head (first element) of this list.
也可以用pop
深度优先算法:用stack,先进后出。
入stack用push:Pushes an element onto the stack represented by this list. In other words, inserts the element at the front of this list. This method is equivalent to addFirst(E)
.
出stack用pop:Pops an element from the stack represented by this list. In other words, removes and returns the first element of this list. This method is equivalent to removeFirst()
.
二者都可以用linkedlist定义,只是使用的时候methods不同,来决定是先进先出,还是先进后出。引用JDK API中关于LinkedList的一句说明:"These operations allow linked lists to be used as a stack, queue, or double-ended queue."由此,可以得知,使用LinkedList可以轻松的实现栈和队列的功能。通过查看LinkedList源码实现,发现其底层采用双向链表实现。
LinkedList<TreeNode> queue = new LinkedList<TreeNode>();
reference:http://www.cnblogs.com/springfor/p/3891391.html
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步