我知道递归会一直执行,直到满足基本情况。
但是,为什么这个递归函数只设置 head 的子节点一次?
当 head 变为 null 时,它返回该节点并将 head 的左子节点或右子节点设置为节点。
我明白了这个概念,但为什么这个递归函数不将所有左子节点或右子节点设置为节点,即使它是递归函数?
还有一个问题,当head为null时,这个递归就停止了,但是这个递归为什么不把null的child设置为节点呢?此递归将 null 的头的前一个子节点设置为节点。这是为什么?
public Node<Integer> insert(Node<Integer> head, Node<Integer> node){
if(head == null){
return node;
}
if(head.getData() >= node.getData()){
head.setLeftChild(insert(head.getLeftChild(), node));
} else {
head.setRightChild(insert(head.getRightChild(), node));
}
return head;
}
最佳答案
我们这里有一个 binary search tree插入功能。
该函数采用两个节点作为参数:head
是二叉树的根,node
是要插入其中的新节点。
新的节点
将以depth-first in-order traversal的方式插入。树的结构将产生整数的升序序列。
why does this recursion function only set head's child once?
它设置从根节点到插入节点位置的路径上的所有树节点,以退出递归。不过,只有第一个分配是有意义的,因为所有其他分配只是设置相同的节点而不进行更改。
why doesn't this recursion function sets all the left children or right children as nodes even though it's recursion function?
此递归中函数的每次调用都会设置左子级、右子级或无子级。如果您仔细跟踪执行过程,您将看到在树中的哪个位置设置了子级。
why doesn't this recursion set null's child as node?
recursion exit condition如果 head
的值为 null
,则阻止对它进行任何操作 - 它返回您想要插入的 node
,而不是返回到上一个递归调用(其中实际插入发生。
关于java - 为什么这个递归函数只设置一次?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48213748/