在通过非递归方式实现查找二叉树的删除后,感觉递归实现查找二叉树非常高大上,体会到递归的优势。
public TreeNode2 findMin(TreeNode2 node){ //找到最小查找二叉树中值最小的节点
if(node == null){
return null;
}
else {
while(node.leftChild != null){
node = node.leftChild;
}
}
return node;
}
public int compareTo(int a, int b){ //比较函数
if(a < b)
return -1;
else if(a > b)
return 1;
else
return 0;
}
public TreeNode2 remove(int x, TreeNode2 t){
if(t == null)
return t;
int compareResult = compareTo(x,t.data); //比较输入值与当前节点的值
if(compareResult < 0)
t.leftChild = remove(x,t.leftChild); //输入值小于当前data,往左递归
else if(compareResult > 0)
t.rightChild = remove(x,t.rightChild); //输入值大于当前data,往右递归
else if(t.leftChild != null && t.rightChild != null){ //输入值与data相等,即找到要删除的节点,此时要删除的节点同时包含左儿子和右儿子
t.data = findMin(t.rightChild).data; //遍历待删除节点的右子树,找到最小值,替换待删除节点的数据值
t.rightChild = remove(t.data,t.rightChild); //递归删除找到的最小值的节点
}
else //在待删除节点最多含有一个子节点时
t = (t.leftChild != null) ? t.leftChild : t.rightChild;
return t;
}