我试图创建一个获取子节点和二叉树的函数,并返回该给定子节点的父节点。如果给定的子节点是根,则它应该返回null。 这就是我想要做的事情:
//input : The function gets a binary tree and a child node
//output : The function returns the parent of a given child of the tree, if the given child is the root
//then it will return null
public static BinTreeNode<Character> Parent(BinTreeNode<Character> bt, BinTreeNode<Character> child){
if(bt==null){
return bt;
}
else{
if(bt.hasLeft()&&(bt.hasRight())){
if((bt.getLeft().getValue()==child.getValue())||(bt.getRight().getValue()==child.getValue())){
return bt;
}
else{
Parent(bt.getLeft(),child);
Parent(bt.getRight(),child);
}
}
if(bt.hasLeft()){
if(bt.getLeft().getValue()==child.getValue()){
return bt;
}
else{
return Parent(bt.getLeft(),child);
}
}
if(bt.hasRight()){
if(bt.getRight().getValue()==child.getValue()){
return bt;
}
else{
return Parent(bt.getRight(),child);
}
}
}
return null;
}
由于某种原因,它一直让我返回null,在调试之后我看到当它到达第一个条件时它检查它是否等于但是然后而不是继续向其他条件的递归以及我告诉它做的只是盯着底部的归零,我不知道为什么? 我将非常感谢任何帮助,我是一种新的java。
答案 0 :(得分:2)
您需要在返回之前穿过树。
你的实现只是向左走,然后返回null(可能你的孩子在右边)......
尝试类似的东西:
public static BinTreeNode<Character> getParent(BinTreeNode<Character>
bt, BinTreeNode<Character> child){
if(bt==null){
return bt;
}
BinTreeNode<Character> left = null;
BinTreeNode<Character> right = null;
if(bt.hasLeft()){
if(bt.getLeft().equals(child))
return bt;
left = getParent(bt.getLeft(),child);
}
if(left == null){
if(bt.hasRight()) {
if(bt.getRight().equals(child))
return bt;
right = getParent(bt.getRight(),child);
}
} else {
return left;
}
return right;
}
这里我们有深度优先搜索的实现。
答案 1 :(得分:0)
问题是你只会检查所有左边的孩子。所以你的代码只适用于左边的孩子(左边的孩子等)。一旦到达底部,您就会返回null
并确认它。
要解决此问题,请将代码更改为以下内容:
public static BinTreeNode<Character> parent(BinTreeNode<Character> bt, BinTreeNode<Character> child) {
if (bt == null) {
return bt;
} else {
if (bt.hasLeft()) {
if (bt.getLeft().equals(child)) {
return bt;
}
BinTreeNode<Character> possibleParent = parent(bt.getLeft(), child);
if (possibleParent != null) {
return possibleParent;
}
}
if (bt.hasRight()) {
if (bt.getRight().equals(child)) {
return bt;
} else {
return parent(bt.getRight(), child);
}
}
return null;
}
}
它会起作用。