具有右侧和左侧子访问的节点树遍历

时间:2017-12-14 20:38:50

标签: java tree traversal

尝试遍历树并为我的数组获取null值。我需要遍历树,该树只允许访问Node类的类定义中没有root的右子节点和左子节点。

class Tree<T> {
 Tree(T x) {
   value = x;
 }
 T value;
 Tree<T> left;
 Tree<T> right;
}

public int[] traverseTree(Tree<Integer> t) {
   Stack<Tree<Integer>> stack = new Stack<Tree<Integer>>();
    Tree<Integer> node = root;

    while (node != null) { 
        stack.push(node);
        node = node.left;
    }

    int[] result = new int[stack.size()];
    int i = 0;
    while (stack.size() > 0) {
        node = stack.pop();
        if(node != null) {
            result[i] = node.value;
            i++;
        }
        if (node.right != null) {
            node = node.right;

            while (node != null) {
                stack.push(node);
                node = node.left;
            }
        }
    }

    return result;
}

需要输入

t = {
"value": 1,
"left": {
    "value": 2,
    "left": null,
    "right": {
        "value": 3,
        "left": null,
        "right": null
    }
},
"right": {
    "value": 4,
    "left": {
        "value": 5,
        "left": null,
        "right": null
    },
    "right": null
   }
 }

这应该返回[1,2,4,3,5]并且我得到[]。我也试过像

这样的循环
 if(root != null) {
     queue.add(root);
  }

 while(root.left != null) {
   while(root.right != null) {
      queue.add(root);
      root = root.right;
   }
   queue.add(root);
   root = root.left;
}

这也不起作用。这也会给我一个[]数组。遍历应该在树高度(即级别)指示的树级别上从左到右打印树。有什么想法吗?

1 个答案:

答案 0 :(得分:0)

  

它应该返回t = [1,2,4,3,5]并且我得到[]。

好吧,让我们看一下您用来填充Queue的for循环:

for (Tree<Integer> node = root; node != null; node = queue.poll()) {
    //stuff
}

你在这里做的是循环,直到queue.poll()返回null,如果我们查看javadoc for ArrayDeque,我们会看到poll()

  

检索并删除此双端队列表示的队列的头部(换句话说,此双端队列的第一个元素),或者如果此双端队列为空则返回null

所以,基本上你循环直到你的Queue为空,然后根据它的大小创建一个数组来返回。由于它的大小始终为零,因此总是返回一个零长度数组。

看起来您正在寻找Preorder遍历,因此您需要做的是使用proper algorithm重写您的方法。

如果您致力于非递归遍历,here's an algorithm就是这样做的。

相关问题