educative.io

WHy following giginv null pointer when assigning root.right.left.left = new TreeNode(11);

Hi I was thinking the following solution for minimum depth

  // TODO: Write your code here
  // Traverse the tree inorder way and then return the number of levels when the leaf node is reached

  // store the nodes in a linked List and return the size of the ll when the last node to add is null

  List<TreeNode> linkedListLeftNodes = new LinkedList();
  List<TreeNode> linkedListRightNodes = new LinkedList();
  int result =0;
  if (root == null) return 1;
  TreeNode currentNode = root;
  linkedListLeftNodes.add(currentNode);
  linkedListRightNodes.add(currentNode);
  while(currentNode.left != null) {
    linkedListLeftNodes.add(currentNode.left);
    if(currentNode.left.left!=null) {
      currentNode.left = currentNode.left.left;
    }
    else if(currentNode.left.right!=null) {
      currentNode.right = currentNode.left.right;
    } else break;
  }

  while(currentNode.right != null) {
    linkedListRightNodes.add(currentNode.right);
    if(currentNode.right.right!=null) {
      currentNode.right = currentNode.right.right;
    }
    else if (currentNode.right.left!=null) {
      currentNode.left = currentNode.right.left;
    } else break;
  }
  result = Math.min(linkedListRightNodes.size(), linkedListLeftNodes.size());
  linkedListRightNodes.clear();
  linkedListLeftNodes.clear();
  return result;
}

Why does the above gives null pointer in the main method when adding root.right.left.left?

TreeNode root = new TreeNode(12);
	    root.left = new TreeNode(7);
	    root.right = new TreeNode(1);
	    root.right.left = new TreeNode(10);
	    root.right.right = new TreeNode(5);
	    System.out.println("Tree Minimum Depth: " + MinimumBinaryTreeDepth.findDepth(root));
	    root.left.left = new TreeNode(9);
	    root.right.left.left = new TreeNode(11);
	    System.out.println("Tree Minimum Depth: " + MinimumBinaryTreeDepth.findDepth(root));