概念
图的遍历有两种遍历方式:深度优先遍历(depth-first search)和广度优先遍历(breadth-first search)。
1.深度优先遍历
基本思路:首先从图中某个顶点V0出发,然后依次从V0相邻的顶点出发深度优先遍历,直至图中所有与V0路径相通的顶点都被访问了;若此时尚有顶点未被访问,则从中选一个顶点作为起始点,重复上述过程,直到所有的顶点都被访问。可以看出深度优先遍历是一个递归的过程。
如下图中的一个无向图:
其深度优先遍历得到的序列为:
0->1->3->7->4->2->5->6
2.广度优先遍历
基本思路:首先,从图的某个顶点V0之后,访问了V0之后,依次访问与V0相邻的未被访问的顶点,然后分别从这些顶点出发,广度优先遍历,直至所有的顶点都被访问完。也是递归的问题。
如上面图中
其广度优先遍历得到的序列:
0->1->2->3->4->2->5->6->7
3.深度优先遍历和广度优先遍历区别
- 广度优先搜索与深度优先搜索的时间复杂度相同,只是遍历顺序不同。
深度优先搜索案例
(Leetcode 173)
* Implement an iterator over a binary search tree (BST). Your iterator will be initialized with the root node of a BST.
* Calling next() will return the next smallest number in the BST.
* Note: next() and hasNext() should run in average O(1) time and uses O(h) memory, where h is the height of the tree.
public class BSTIterator { private List<Integer> list = new ArrayList<Integer>(); int cursor = -1; public static class TreeNode{ int val; TreeNode left; TreeNode right; public TreeNode(int val) { this.val = val; } } /** * Your BSTIterator will be called like this: * BSTIterator i = new BSTIterator(root); * while (i.hasNext()) v[f()] = i.next(); */ public BSTIterator(TreeNode root) { helper(root); } private void helper(TreeNode root) { if (root == null){ return; } helper(root.left); list.add(root.val); helper(root.right); } /** @return whether we have a next smallest number */ public boolean hasNext() { if (cursor < list.size()-1) return true; else return false; } /** @return the next smallest number */ public int next() { cursor++; return list.get(cursor); } }
广度搜索举例
Leetcode 199
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]
]
树节点的定义:
private class TreeNode{ int val; TreeNode left; TreeNode right; public TreeNode(int val) { this.val = val; } }
广度优先搜索遍历:
public List<List<Integer>> levelOrder(TreeNode root) { List<List<Integer>> result = new ArrayList<List<Integer>>(); List<TreeNode> layer = new ArrayList<TreeNode>(); if (root != null){ layer.add(root); } while (!layer.isEmpty()){ List<Integer> vals = new ArrayList<Integer>(); List<TreeNode> temp = new ArrayList<TreeNode>(); for (int i = 0; i < layer.size(); i++) { vals.add(layer.get(i).val); TreeNode left = layer.get(i).left; TreeNode right = layer.get(i).right; if (left != null){ temp.add(left); } if (right != null){ temp.add(right); } } result.add(vals); layer = temp; } return result; }