我试图将我的inorder traversal的结果存储在linkedlist中,并通过迭代器检索,但是在打印结果时获得了无指针异常。当我尝试通过递归和打印功能打印值进行操作时,我会得到正确的输出。当我递归地尝试调用inorderItr(root.left)
时,它将root
作为null。我认为,我的返回声明不正确,不确定以下是我的代码和我的代码打破的地方。任何帮助和概念都将受到赞赏。我已经看到了这一点,但没有帮助,因为我试图返回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 + " ");
}
}
}
我已经创建了一个用于机中遍历和全局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);
}