深度优先遍历和广度优先遍历
1.时间复杂度
对于图,深度优先搜索的时间复杂度和广度优先搜索的时间复杂度是一样的,邻接矩阵存储为O(n^2), 邻接表存储为O(n+e) ;
对于树,深度优先搜索的时间复杂度和广度优先搜索的时间复杂度是一样的,都是O(V),V是树的节点数。
2.基于树的 代码实现
1 public class DepthFirstTraversal { 2 public static void main(String[] args) { 3 TreeNode root = new TreeNode(1); 4 root.left = new TreeNode(2); 5 root.right = new TreeNode(3); 6 root.left.left = new TreeNode(4); 7 root.left.right = new TreeNode(5); 8 root.right.left = new TreeNode(6); 9 root.right.right = new TreeNode(7); 10 // preOrderTraverse2(root); 11 levelTraverse(root); 12 } 13 // 1.先序遍历 递归实现 14 public static void preOrderTraverse1(TreeNode root){ 15 if(root==null)return; 16 System.out.print(root.val+" "); 17 preOrderTraverse1(root.left); 18 preOrderTraverse1(root.right); 19 } 20 // 2.先序遍历 非递归实现---栈 21 public static void preOrderTraverse2(TreeNode root) { 22 if(root==null)return; 23 Stack<TreeNode> stack = new Stack<>(); 24 stack.push(root); 25 while(!stack.isEmpty()){ 26 TreeNode node = stack.pop(); 27 System.out.print(node.val+" "); 28 if(node.right!=null) stack.push(node.right); 29 if(node.left!=null) stack.push(node.left); 30 } 31 } 32 // 3.层次遍历 33 public static void levelTraverse(TreeNode root) { 34 if(root==null) return; 35 LinkedList<TreeNode> queue = new LinkedList<>(); 36 queue.offer(root); 37 while(!queue.isEmpty()){ 38 TreeNode node = queue.poll(); 39 System.out.print(node.val+" "); 40 if(node.left!=null) queue.offer(node.left); 41 if (node.right!=null) queue.offer(node.right); 42 } 43 } 44 }