【发布时间】:2018-09-15 11:46:33
【问题描述】:
我正在尝试实现二叉树而不是二叉搜索树。我花了很多时间使用递归编写插入操作,但没有得到。
它应该是一棵从左到右填充的完整树。
有人可以帮助我吗?最好是在 Java 中。
以下是迭代的方法。(:(这甚至不起作用))
public static void insertNode(Node root,int x){
if(root==null) {
root = new Node(x);
return;
}
Node current;
Queue<Node> qq = new LinkedList<Node>();
((LinkedList<Node>) qq).push(root);
while(true){
current=qq.peek();
if(current.leftchild==null){
Node child = new Node(x);
child.parent = current;
current.leftchild=child;
return;
}
else { ((LinkedList<Node>) qq).push(current.leftchild);}
if(current.rightChild==null){
Node child = new Node(x);
child.parent=current;
current.rightChild=child;
return;
}
else{
((LinkedList<Node>) qq).push(current.rightChild);
}
((LinkedList<Node>) qq).pop();
}
【问题讨论】:
-
你好,欢迎来到 StackOverflow,这个问题没有提供足够的信息,总是尝试提供一些与你迄今为止用你的一些代码尝试过的东西以及你卡在哪里的信息。帮助人们帮助你。也可以看看:stackoverflow.com/tour
-
这是一个基本问题,如何进行插入操作。我相信这个问题很清楚。不是吗?
-
如我的评论中所述,请分享您到目前为止尝试了什么,什么没有奏效?你总是需要提供一个最简单的例子来说明什么是行不通的。
-
@ZeeshanAdil... 我按照你的建议做了。
-
递归的意义何在?如果插入二叉树,只需将新节点设为树根
标签: java data-structures binary-tree