如何迭代二叉树? [英] How do I iterate over Binary Tree?

查看:35
本文介绍了如何迭代二叉树?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

现在我有

 private static void iterateall(BinaryTree foo) {
    if(foo!= null){
    System.out.println(foo.node);
    iterateall(foo.left);
    iterateall(foo.right);
   }
  }

你能把它改成迭代而不是递归吗?

Can you change it to Iteration instead of a recursion?

推荐答案

你能把它改成迭代而不是递归吗?

Can you change it to Iteration instead of a recursion?

您可以使用显式堆栈.伪代码:

You can, using an explicit stack. Pseudocode:

private static void iterateall(BinaryTree foo) {
    Stack<BinaryTree> nodes = new Stack<BinaryTree>();
    nodes.push(foo);
    while (!nodes.isEmpty()) {
        BinaryTree node = nodes.pop();
        if (node == null)
            continue;
        System.out.println(node.node);
        nodes.push(node.right);
        nodes.push(node.left);
    }
}

但这并没有真正优于递归代码(除了代码中缺少的基本条件).

But this isn’t really superior to the recursive code (except for the missing base condition in your code).

这篇关于如何迭代二叉树?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆