将二叉树转换为双链表-Java

时间:2018-11-16 21:08:19

标签: java nullpointerexception binary-tree traversal

请帮助我解决这个问题。它取自Educative.io课程“ Coderust 3.0:更快的编码面试准备”

问题描述:

将二叉树转换为双向链表,使得双向链表的顺序与对二进制树的有序遍历相同。转换后,该节点的左指针应指向双向链接列表中的前一个节点,而右指针应指向双向链接列表中的下一个节点。

Here's a visualization of the problem

我的代码:

class toDLL{
  public static BinaryTreeNode convert_to_linked_list(BinaryTreeNode root) {

    Stack<BinaryTreeNode> stack = new Stack<>();
    BinaryTreeNode head = root;
    if(root == null) return head;

    while(root != null) {
      head = root;
      stack.push(root);
      root = root.left;
    }

    while(!stack.isEmpty()) {
      BinaryTreeNode temp = stack.pop();
      BinaryTreeNode cur = temp;

      cur = cur.right;
      while(cur != null) {
         stack.push(cur);
        cur = cur.left;
      }
      if(!stack.isEmpty()) {
        temp.right = stack.peek();
        stack.peek().left = temp;
      }
    }
    return head;
  }
}  

当我在educative.io编译器中运行它时,出现以下错误:

Exception in thread "main" java.lang.NullPointerException
    at BinaryTree.get_list(*.java:39)
    at EdTestRunner.executeTests(*.java:374)
    at TestRunner.main(*.java:401)

但是,当我使用自己的BinaryTreeNode类实现在Eclipse中运行它时,我没有遇到任何错误。我在该课程上的代码很长,因此我相信不需要在这里添加它?

当我进行如此多的检查以查看堆栈是否在执行任何操作之前是否为空时,我看不到Null指针异常。

请帮助

0 个答案:

没有答案
相关问题