• 樹的DFS和BFS


    菜鸟心得.... 不对请指出.......







    /*
    BFS,广度优先搜索树,用最简单的2叉树来举例, 树的结构如下:
         A
        B C
     D E F G
    H I J K L M N O
    广度优先搜索树, 顺序应该是ABCDEFGHIJKLMNO;
    意思是,先搜索完 上一层的节点,再开始搜索下一层的节点;
    那么在BFS中, 会使用到一种数据结构----队列
    队列的特点是,先进先出, 就像一条水管一样,这头进,那头出。
    尾----------------------头
    ->> F E D C B A ->>>
    -------------------------
    从左边进去,只能从右边出来, 而先进去的,总是会先出来。
    利用队列的这个特点。
    1,先把根节点放进队列中。
    当队列不为空时,执行下列234,否则结束。
    2,取出队列的头,判断其value是否和x相同(X为要找的值),如果是,结束,否则删除 头元素 继续下一步。
    3,判断左子树是否为空,不为空,将左子树放进队列。
    4,判断右子树是否为空,不为空,将右子树放进队列。
    */
    1
    import java.util.Queue; 3 public class BFS { 4 class tree { 5 tree left; 6 tree right; 7 int value; 8 9 public tree(int value) { 10 this.value = value; 11 } 12 } 13 14 private Queue<tree> queue = new LinkedList<tree>(); 15 16 public void solution(tree node, int x) { 17 queue.offer(node); 18 if (!queue.isEmpty()) { 19 if (queue.peek().value != x) { 20 queue.remove(); 21 if (node.left != null) { 22 queue.add(node.left); 23 } 24 if (node.right != null) { 25 queue.add(node.right); 26 } 27 } 28 } 29 } 30 31 }

     /*
    DFS,深度优先搜索树,还是用最简单的二叉树来举例,
    用最简单的办法,递归遍历。
    或者适用 stack这数据结构。
    */
    1
    import java.util.Stack; 2 3 public class dfs { 4 class tree { 5 tree left; 6 tree right; 7 int value; 8 9 public tree(int value) { 10 this.value = value; 11 } 12 } 13 14 private Stack<tree> stack = new Stack<tree>(); 15 16 public void solution(tree node, int x) { 17 stack.push(node); 18 if (!stack.isEmpty()) { 19 if (stack.peek().value != x) { 20 stack.pop(); 21 if (node.right != null) { 22 stack.add(node.right); 23 } 24 if (node.left != null) { 25 stack.add(node.left); 26 } 27 } 28 } 29 } 30 31 public void solution2(tree node, int x) { 32 if (node.value != x) { 33 if (node.left != null) { 34 solution2(node.left, x); 35 } else if (node.right != null) { 36 solution2(node.left, x); 37 } 38 } 39 } 40 }
  • 相关阅读:
    matplotlib 可视化 —— matplotlib.patches
    Ansi,UTF8,Unicode,ASCII编码的差别
    java.lang.Runnable接口
    wikioi 1051哈希表
    具体解释协方差与协方差矩阵
    基于Android Fragment功能的样例
    大学让我们坠落
    FFTW库+VS2012配置
    Ubuntu下安装eclipse
    SoftReference
  • 原文地址:https://www.cnblogs.com/YYfish/p/5659461.html
Copyright © 2020-2023  润新知