我如何遍历二叉树? [英] How do I iterate over Binary Tree?

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

问题描述

现在我有

 私有静态无效iterateall(二叉树富){
    如果(FOO!= NULL){
    的System.out.println(foo.node);
    iterateall(foo.left);
    iterateall(foo.right);
   }
  }
 

您可以将其更改为迭代递归的呢?

解决方案
  

您可以将其更改为迭代递归的呢?

您可以使用一个明确的堆栈。伪code:

 私有静态无效iterateall(二叉树富){
    堆叠<二叉树>节点=新的堆栈<二叉树>();
    nodes.push(富);
    而(!nodes.isEmpty()){
        二叉树结点= nodes.pop();
        如果(节点== NULL)
            继续;
        的System.out.println(node.node);
        nodes.push(node.right);
        nodes.push(node.left);
    }
}
 

但是,这是不是真的优于递归code(除非你的code缺少基本条件)。

Right now I have

 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天全站免登陆