在开发的过程中用到了遍历树的方法。没有使用递归,而是采用栈顶方式实现的。
把代码贴在这里,如果大家用到,可以参考一下。
这里,树是一般的树结构,不单指二叉树。
- public class Tool{
-
- 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;
-
- public TreeNode(TreeNode father, int value) {
- this.father = father;
- this.value = value;
- }
- }
欢迎大家批评指正。
发表于 @ 2008年09月01日 11:33:00|评论(loading...)|编辑|收藏