I am trying to store my results of Inorder traversal in an LinkedList and retrieve by iterator, but getting null pointer exception while printing my results. I get correct output when I try to do it by recursion and print value in my function. When I recursively try to call inorderItr(root.left)
, it takes root
as null. I think, my return statement is not correct, Not sure, below is my code and comments where my code is breaking. Any help and concepts are appreciated. I have seen this, but doesnt help, as I am trying to return an Iterator
. Again, I am new to Java and Iterator
concept. TIA.
Edit: I have found the solution, please see the answer below
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 + " ");
}
}
}
I have created a helper method for inorder traversal and Global LinkedList and added all my Inorder elements to that list in a separate recursive helper method. That way we can return an Iterator
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);
}