如何在二叉树中返回迭代遍历的迭代器?

问题描述 投票:0回答:1

我试图将我的Inorder遍历结果存储在LinkedList中并通过迭代器检索,但在打印结果时获取空指针异常。当我尝试通过递归和函数中的打印值来获取正确的输出时。当我递归地尝试调用inorderItr(root.left)时,它需要root为null。我认为,我的return语句不正确,不确定,下面是我的代码和注释,我的代码在哪里破解。任何帮助和概念表示赞赏。我见过this,但没有帮助,因为我试图返回一个Iterator。同样,我是Java和Iterator概念的新手。 TIA。

编辑:我找到了解决方案,请参阅下面的答案

  class TreeNode {

            int data;
            TreeNode left;
            TreeNode right;

            public TreeNode(int d) {
                data = d;
            }

        }

        public class TreeTraversal {
             TreeNode root;

            public TreeTraversal() {
                root = null;
            }

       static List<TreeNode> l = new LinkedList<TreeNode>();
            public static Iterator<TreeNode> inorderItr(TreeNode root) {

                List<TreeNode> l = new LinkedList<TreeNode>();

      //I think I am missing something here
                if (root == null)
                    return

      //This is where my root is null
                inorderItr(root.left);
                l.add(root);
                inorderItr(root.right);

                Iterator<TreeNode> itr = l.iterator();

                return itr;

            }

    //This code works fine
            public static void inorderWorksFine(TreeNode root) {

                if (root == null)
                    return;

                inorder(root.left);
                System.out.print(root.data + " ");
                inorder(root.right);
            }



            public static void main(String args[]) {

                TreeTraversal t = new TreeTraversal();
                t.root = new TreeNode(10);
                t.root.left = new TreeNode(5);
                t.root.left.left = new TreeNode(1);
                t.root.left.right = new TreeNode(7);
                t.root.right = new TreeNode(40);
                t.root.right.right = new TreeNode(50);

                // inorderWorksFine(t.root);
                Iterator<TreeNode> itr = inorderItr(t.root);

                while (itr.hasNext()) {
                    System.out.println(itr.next().data + " ");
                }

            }

        }
java iterator binary-tree inorder
1个回答
1
投票

我为inorder遍历和Global LinkedList创建了一个辅助方法,并在一个单独的递归帮助方法中将所有的Inorder元素添加到该列表中。这样我们就可以返回迭代器了

static List<TreeNode> l = new LinkedList<TreeNode>();

    public static Iterator<TreeNode> inorderItr(TreeNode root) {
    recursionInorder(root);
    Iterator<TreeNode> itr = l.iterator();

     return itr;

    }

    public static void recursionInorder(TreeNode node){
        if(node==null)
              return;

        recursionInorder(node.left);
        l.add(node);
        recursionInorder(node.right);
    }
© www.soinside.com 2019 - 2024. All rights reserved.