我遇到了一个遍历遍历的二叉搜索树函数,但无法解决。这是代码:
public void inOrderTraverseTree(Node focusNode){
if(focusNode != null){
inOrderTraverseTree(focusNode.leftChild);
System.out.println(focusNode);
inOrderTraverseTree(focusNode.rightChild);
}
}
假设一个“两级”平衡二进制搜索树,这就是我对这种递归方法的理解:
root != null
开始-> inOrderTraverseTree(root.leftChild)
方法运行root.leftChild != null
-> inOrderTraverseTree(root.leftChild.leftChild)
方法正在运行root.leftChild
没有leftChild-> focusNode.leftChild == null
,因此if
循环将不会运行但是它可以正常工作(https://www.youtube.com/watch?v=M6lYob8STMI)。谁能指出我哪里出问题了?
答案 0 :(得分:3)
此处应用的逻辑:
检查焦点节点。如果null
,则return
到父级的inOrderTraverseTree
。但是,由于在检查null之后没有任何反应,因此附加的return
语句与根本没有语句一样。
如果不是null
,请从(1)重复左子节点。
打印焦点节点的值。
从(1)重复右子节点。
从当前节点的inOrderTraverseTree
返回到父节点的inOrderTraverseTree
。
当然,如果关注的节点是root
节点,则inOrderTraverseTree
会简单地返回到main
或首先调用它的方法
作为一个例子,考虑下面的树:
A
/ \
B C
/ \ / \
D E F G
踪迹:
A->inOrderTraverseTree(left)
B->inOrderTraverseTree(left)
D->inOrderTraverseTree(left) //null, return to D
print(D)
D->inOrderTraverseTree(right) //null, return to D
return to B
print(B)
B->inOrderTraverseTree(right)
E->inOrderTraverseTree(left) //null, return to E
print(E)
E->inOrderTraverseTree(right) //null, return to E
return to B
return to A
print(A)
A->inOrderTraverseTree(right)
//Continue for the right subtree.
答案 1 :(得分:0)
但是,由于root.leftChild没有
leftChild
->focusNode.leftChild
== null
,if循环将不会运行
不,它将。由于它是递归的,因此它将继续执行以前的调用,在这种情况下,请检查righchild节点。
观察函数的调用顺序:
它继续...
答案 2 :(得分:0)
您需要在此处了解基本的递归和二进制搜索树结构。让我们从下面的树中了解该算法:
1. Focus Node is 9 , since it is not null, thus , inOrderTraverseTree
is invoked with focus node as 7(with left node to 9)
2. Focus Node is 7 , since it is not null, thus , inOrderTraverseTree is invoked with focus node as null(with left
node to 7)
3. Focus Node is null , thus , if condition is not satisfied and execution of function call at step 2 continues.
4. Control goes to method call with node as 7 (since left node was blank) and 7 is printed at System.out.println statement.
5. Now inOrderTraverseTree for focus node null is invoked (with right node to 7)
6. Focus Node is null , thus , if condition is not satisfied and execution of function call at step 2 continues.
7. inOrderTraverseTree for focus node 2 exits and control goes to method call with node as 9.
8. Control goes to method call with node as 9 and 9 is printed at System.out.println statement.
9. inOrderTraverseTree for focus node 11 is invoked (with right node to 9)
10.inOrderTraverseTree for focus node null is invoked (with left node to 11), thus, if condition is not satisfied and control is sent
back to step 9
11. Control goes to method call with node as 11 and 11 is printed at System.out.println statement.
12.inOrderTraverseTree for focus node null is invoked (with right node to 11), thus, if condition is not satisfied and control is sent
back to step 9.
执行结束