小编Jav*_*ail的帖子

Java使用特定格式的级别顺序打印二叉树

好的,我已经阅读了所有其他相关问题,但找不到有助于java的问题.我从破译其他语言的内容中得到了一般性的想法; 但我还没搞清楚.

问题:我想进行排序(我使用递归工作)并将其打印出树的一般形状.

所以说我有这个:

    1 
   / \
  2   3
 /   / \
4   5   6
Run Code Online (Sandbox Code Playgroud)

我的代码打印出这样的级别顺序:

1 2 3 4 5 6
Run Code Online (Sandbox Code Playgroud)

我想像这样打印出来:

1
2 3
4 5 6
Run Code Online (Sandbox Code Playgroud)

在你给我一个关于做我的工作的道德讲话之前......我已经完成了我的AP Comp Sci项目并且当我的老师提到了广度优先搜索的东西时对此感到好奇.

我不知道它是否会有所帮助,但到目前为止我的代码是:

/**
  * Calls the levelOrder helper method and prints out in levelOrder.
  */
 public void levelOrder()
 {
  q = new QueueList();
  treeHeight = height();
  levelOrder(myRoot, q, myLevel);
 }

 /**
  * Helper method that uses recursion to print out the tree in 
  * levelOrder
  */
 private void levelOrder(TreeNode …
Run Code Online (Sandbox Code Playgroud)

java format binary-tree order-of-execution

17
推荐指数
4
解决办法
7万
查看次数

遍历树以查找节点

我正在搜索树以查找传递的值.不幸的是,它不起作用.我开始用打印机调试它,奇怪的是它实际上找到了值,但是跳过了return语句.

    /**
  * Returns the node with the passed value
  */
 private TreeNode searchNodeBeingDeleted(Comparable c, TreeNode node)
 {  
  if(node == null) 
  {
   return null;
  }

  if(c.equals((Comparable)node.getValue()))
  {
   System.out.println("Here");
   return node;
  }
  else
  {
   if(node.getLeft() != null)
   {
    System.out.println("left");
    searchNodeBeingDeleted(c, node.getLeft());
   }
   if(node.getRight() != null)
   {
    System.out.println("right");
    searchNodeBeingDeleted(c, node.getRight());
   }
  }
  return null; //i think this gives me my null pointer at bottom
 }
Run Code Online (Sandbox Code Playgroud)

它打印出如下结果:

left
left
right
right
Here
right
left
right
left
right
Exception in thread "main" java.lang.NullPointerException
at …
Run Code Online (Sandbox Code Playgroud)

java algorithm recursion binary-tree

5
推荐指数
1
解决办法
3810
查看次数