我试图将中序遍历的结果存储在 LinkedList 中并通过迭代器检索,但在打印结果时出现空指针异常。当我尝试通过递归并在函数中打印值时,我得到正确的输出。当我递归地尝试调用 inorderItr(root.left)
时,它会将 root
视为 null。我认为,我的返回语句不正确,不确定,下面是我的代码和注释,其中我的代码被破坏。任何帮助和概念表示赞赏。我见过this ,但没有帮助,因为我正在尝试返回一个迭代器。再说一遍,我对 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 + " ");
}
}
}
最佳答案
我创建了一个用于中序遍历和全局 LinkedList 的辅助方法,并在单独的递归辅助方法中将所有中序元素添加到该列表中。这样我们就可以返回一个迭代器
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);
}
关于java - 如何返回二叉树中序遍历的迭代器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47918045/