【问题标题】:Implement Binary Tree Iterator search Method, which is travel in order through Tree in Java实现二叉树迭代器搜索方法,在Java中按顺序遍历树
【发布时间】:2020-12-12 21:00:11
【问题描述】:

我必须为二叉树实现一个自定义迭代器,“下一个方法”正在对二叉树进行排序。我不允许使用任何 java.util 包,所以我不能为此使用堆栈。

@Override
    public T next() {
        T result = node.data;
        if (node.rightChild != null) {
            node = smallest(node.rightChild);
        } else {
            node = node.parent;
        }
        return result;
    }



    private Nodes<T> smallest(Nodes<T> n) {
        if (n.leftChild != null) {
            return smallest(n.leftChild);
        } else {
            return n;
        }
    } 

目前,他只是迭代,直到没有更多的 rightChild。你能帮我完成“下一个方法”吗?

谢谢大家

【问题讨论】:

    标签: java iterator inorder


    【解决方案1】:

    经过大量测试,这是我的解决方案,效果很好。如果有人需要完整的代码,请询问

     @Override
        public T next() {
            T result = node.data;
            if (node.rightChild != null) {
                node = smallest(node.rightChild);
            } else {
                while (node.parent != null && node != node.parent.leftChild){
                    node = node.parent;
                }
                node = node.parent;
            }
            return result;
        }
    
    
        private Nodes<T> smallest(Nodes<T> n) {
            if (n.leftChild != null) {
                return smallest(n.leftChild);
            } else {
                return n;
            }
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-06-23
      • 2017-05-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-06-02
      • 1970-01-01
      • 2018-02-25
      相关资源
      最近更新 更多