首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >泛型PostOrder ( BinarySearchTree )中的BinarySearchTree输出

泛型PostOrder ( BinarySearchTree )中的BinarySearchTree输出
EN

Stack Overflow用户
提问于 2017-04-12 20:30:49
回答 1查看 78关注 0票数 0

我在做一些编码作业时遇到了一点小麻烦。我应该编写一个通用的二进制搜索树实用程序,包括一个返回树的ArrayList遍历版本的postOrder的方法。我的代码编译,但是它为除空树之外的所有树抛出一个NullPointerException。我的错误在哪里?

代码语言:javascript
复制
public ArrayList<T> postOrder(BinarySearchTree<T> tree) {
    if (tree == null) {
        return null;
    } else {
        ArrayList<T> post = new ArrayList<T>();
        post.addAll(postOrder(tree.left));
        post.addAll(postOrder(tree.right));
        post.add(tree.thing);
        return post;
    }
}

BinarySearchTree类是:

代码语言:javascript
复制
public class BinarySearchTree<T> {
/**
 * The key by which the thing is refered to. Must be unique.
 */
public int key;

/**
 * The thing itself.
 */
public T thing;

/**
 * The left sub-tree
 */
public BinarySearchTree<T> left;

/**
 * The right sub-tree
 */
public BinarySearchTree<T> right;
Biny
/**
 * Create a new binary search tree without children.
 * @param key the key by which the thing is refered to
 * @param thing the new thing
 */
public BinarySearchTree(int key, T thing)
{
    this.key = key;
    this.thing = thing;
    this.left = null;
    this.right = null;
}

/**
 * Create a new binary search tree
 * @param key the key by which the thing is refered to
 * @param thing the thing which is managed by the new binary search tree
 * @param left the left sub-tree of the new binary search tree
 * @param right the right sub-tree of the new binary search tree
 */
public BinarySearchTree(int key, T thing, BinarySearchTree<T> left, BinarySearchTree<T> right)
{
    this.key = key;
    this.thing = thing;
    this.left = left;
    this.right = right;
}

谢谢你的帮助

编辑:我正在用Strings测试我的代码,但希望这并不重要,因为我使用的是泛型类型。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-04-12 20:50:20

试试这个:

代码语言:javascript
复制
public ArrayList<T> postOrder(BinarySearchTree<T> tree) {
    if (tree == null) {
        return null;
    } else {
        ArrayList<T> post = new ArrayList<T>();
        ArrayList<T> l = postOrder(tree.left);
        if (l != null) post.addAll(l);
        ArrayList<T> r = postOrder(tree.right);
        if (r != null) post.addAll(r);
        post.add(tree.thing);
        return post;
    }
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/43379105

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档