【发布时间】:2015-07-21 02:03:20
【问题描述】:
我正在尝试编写一个二叉树递归插入,但在过去的几个小时里我什么也没有。我要么收到 stackoverflow 错误,要么没有插入所有项目。
我想在我的树中插入这些值:
binaryTree.addNodeRecursion(new MNode(50, "fourth"))
binaryTree.addNodeRecursion(new MNode(25, "third"))
binaryTree.addNodeRecursion(new MNode(15, "second"))
binaryTree.addNodeRecursion(new MNode(10, "first"))
binaryTree.addNodeRecursion(new MNode(75, "fifth"))
binaryTree.addNodeRecursion(new MNode(85, "sixth"))
我想在不将根作为参数传递的情况下执行此操作。所以我的代码如下所示:
public void addNodeRecursion(MNode newNode){
if(root == null) {
root = newNode
}else{
addRecurs(newNode); //this is the recursive function, it should not return a node object
}
}
请注意,我说的不是二叉搜索树,而是二叉树,其中元素顺序无关紧要。我关心如何插入元素。我想插入它们,如下所示:
1 Step:
50
2 Step:
50
/
25
3 Step:
50
/ \
25 15
4 Step:
50
/ \
25 15
/
10
5 Step:
50
/ \
25 15
/ \
10 75
6 Step: (now notice that I am going back to the sibling of the current parent)
50
/ \
25 15
/ \ /
10 75 85
现在这是我的addRecurs 函数:
private void addRecurs(MNode newNode) {
if(newNode == null) { return };
if(root.leftNode == null){ //Step 2 if the left node is null assign it
root.leftNode = newNode
}else{ //Else that means the right Node is null
root.rightNode = newNode // Step 3 set the right node
root = root.leftNode // the the parent to the left node
addRecurs(newNode) // repeat
}
};
它不起作用。
这可以在不跟踪或将父级存储在变量中的情况下完成吗?
【问题讨论】:
-
你有一个简单完整的例子来说明你的问题吗?
-
不,这只是我在空闲时间尝试做的事情。我自己提出了这个问题并试图解决它。主要问题是我想按照我在步骤中展示的特定顺序插入元素