在开发的过程中用到了遍历树的方法。没有使用递归,而是采用栈顶方式实现的。
把代码贴在这里,如果大家用到,可以参考一下。
这里,树是一般的树结构,不单指二叉树。
- public class Tool{
- /**
- * 利用栈遍历树,判断树中有没有和参数相同的节点
- *
- * @param root
- * @return
- */
- public boolean hasSameInTree(TreeNode root, int value) {
- Stack stack = new Stack();
- stack.push(root);
- TreeNode temp = null;
- while (true) {
- if (temp != null) {
- if (temp.value == value) {
- return true;
- }
- if (temp.kids != null) {
- for (int i = 0; i <= temp.kids.length - 1; i++) {
- stack.push(temp.kids[i]);
- }
- temp = null;
- } else {
- if (stack.size() > 0) {
- temp = (TreeNode) stack.pop();
- } else {
- temp = null;
- }
- }
- }
- if (stack.size() > 0 && temp == null) {
- temp = (TreeNode) stack.pop();
- }
- if (temp == null) {
- return false;
- }
- }
- }
- }
- private class TreeNode {
- /**
- * 父节点的引用
- */
- public TreeNode father;
- /**
- * 保存的数值
- */
- public int value;
- /**
- * 子节点的引用的数组
- */
- public TreeNode[] kids;
- /**
- * 构造函数
- *
- * @param father
- * @param gen
- * @param dir
- * @param pos
- */
- public TreeNode(TreeNode father, int value) {
- this.father = father;
- this.value = value;
- }
- }
欢迎大家批评指正。