有个很有名的算法叫广度优先搜索(Breadth-First Search)BFS,这个算法被用于遍历或者搜索数据结构,比如树或者图。
BFS使用到树上就是level-order traversal.
进行广度优先搜索算法时,需要用到java的Queue,Queue是继承自Collection的,所以Collection中的方法都是可以用的。
Queue常用方法:offer、poll、size、isEmpty等
LeetCode中level-order traversal的例子:
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public List<List<Integer>> levelOrder(TreeNode root) {
List<List<Integer>> ans = new ArrayList<>();
Queue<TreeNode> q = new LinkedList<>();
if (root != null) {
q.offer(root);
}
TreeNode cur;
while (!q.isEmpty()) {
int size = q.size();
List<Integer> subAns = new LinkedList<Integer>();
for (int i = 0; i < size; ++i) { // traverse nodes in the same level
cur = q.poll();
subAns.add(cur.val); // visit the root
if (cur.left != null) {
q.offer(cur.left); // push left child to queue if it is not null
}
if (cur.right != null) {
q.offer(cur.right); // push right child to queue if it is not null
}
}
ans.add(subAns);
}
return ans;
}
}
Since each node in the tree will be pushed into the queue exactly once, the time complexity for level-order traversal is O(N)
, where N
is the total number of nodes in the tree.
What about the space complexity? We have to maintain a queue to help us to do the traversal. And the size of the queue will be at most N
because each node will be pushed into the queue exactly once. Therefore, the space complexity of level-order traversal is also O(N)
.
还有另一个算法是深度优先搜索(Depth-First Search)DFS,这个可以有两种实现方案,可以用递归实现也可以用迭代实现。
比较简单,可以看下面的参考
总体说,深度操作(深度优先遍历、先序、中序和后序)既可以用递归实现也可以用迭代实现,迭代实现需要用到栈。广度操作好像只能用迭代实现,需要用到队列。
参考: