非递归遍历树

来源:互联网 发布:matlab约束粒子群算法 编辑:程序博客网 时间:2024/04/30 14:37

    在开发的过程中用到了遍历树的方法。没有使用递归,而是采用栈顶方式实现的。

    把代码贴在这里,如果大家用到,可以参考一下。

    这里,树是一般的树结构,不单指二叉树。

  1. public class Tool{  
  2.     /**
  3.      * 利用栈遍历树,判断树中有没有和参数相同的节点
  4.      * 
  5.      * @param root
  6.      * @return
  7.      */
  8.     public boolean hasSameInTree(TreeNode root, int value) {
  9.         Stack stack = new Stack();
  10.         stack.push(root);
  11.         TreeNode temp = null;
  12.         while (true) {
  13.             if (temp != null) {
  14.                 if (temp.value == value) {
  15.                     return true;
  16.                 }
  17.                 if (temp.kids != null) {
  18.                     for (int i = 0; i <= temp.kids.length - 1; i++) {
  19.                         stack.push(temp.kids[i]);
  20.                     }
  21.                     temp = null;
  22.                 } else {
  23.                     if (stack.size() > 0) {
  24.                         temp = (TreeNode) stack.pop();
  25.                     } else {
  26.                         temp = null;
  27.                     }
  28.                 }
  29.             }
  30.             if (stack.size() > 0 && temp == null) {
  31.                 temp = (TreeNode) stack.pop();
  32.             }
  33.             if (temp == null) {
  34.                 return false;
  35.             }
  36.         }
  37.     }
  38. }
  39. private class TreeNode {
  40.     /**
  41.      * 父节点的引用
  42.      */
  43.     public TreeNode father;
  44.     /**
  45.      * 保存的数值
  46.      */
  47.     public int value;
  48.     /**
  49.      * 子节点的引用的数组
  50.      */
  51.     public TreeNode[] kids;
  52.     /**
  53.      * 构造函数
  54.      * 
  55.      * @param father
  56.      * @param gen
  57.      * @param dir
  58.      * @param pos
  59.      */
  60.     public TreeNode(TreeNode father, int value) {
  61.         this.father = father;
  62.         this.value = value;
  63.     }
  64. }

    欢迎大家批评指正。

原创粉丝点击