作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我试图将中序遍历的结果存储在 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/
序 大家好呀,我是summo,这次来写写我在上班空闲(摸鱼)的时候做的一个小网站的事。去年阿里云不是推出了个活动嘛,2核2G的云服务器一年只要99块钱,懂行的人应该知道这个价格在业界已经是非常良心了
我尝试根据给定的级别顺序(BFS 顺序)构造 BST。我知道这是可能的,但我不知道我该怎么写。问题是我必须使用 BFS 序列。所以,我不能在这里使用递归,我必须迭代地编写我的程序......我发现这有
我是一名优秀的程序员,十分优秀!