这是一个递归函数(一个反复调用自身的函数)。 return 的目的是确保它不会尝试永远这样做,从而在您从树的底部运行时导致空指针异常。
会发生的是,当你第一次用一个节点(通常但不总是根节点)调用这个函数时,它会首先打印出那个节点的左子树,然后是节点的值本身,然后是该节点的右子树。
它打印出子树的方式是使用该子树的顶级节点调用自身。这是优雅处理递归结构的一种非常常用的方法。
null 的测试是这样的,它具有这样一个条件,即当它到达您正在检查的特定一侧(左侧或右侧)没有子节点时,停止向下搜索树的级别。
举例来说,假设您有以下树(带有数字的大写字母是实节点,数字是它们的值,=== 标记是空值):
A26 Level 0
|
+------+------+
| |
B14 C84 Level 1
| |
+--+--+ +--+--+
| | | |
D11 === === E99 Level 2
| |
+--+--+ +--+--+
| | | |
=== === === === Level 3
当您使用 A 调用函数时,会发生以下情况。
You call the function (level 0) with A.
The function will call itself (level 1) with B (A left).
The function will call itself (level 2) with D (B left).
The function will call itself (level 3) with null (D left).
The function will return to level 2.
The function will print out 11 from D.
The function will call itself (level 3) with null (D right).
The function will return to level 2.
The function will return to level 1.
The function will print out 14 from B.
The function will call itself (level 2) with null (B right).
The function will return to level 1.
The function will return to level 0.
The function will print out 26 from A.
The function will call itself (level 1) with C (A right).
The function will call itself (level 2) with null (C left).
The function will return to level 1.
The function will print out 84 from C.
The function will call itself (level 2) with E (C right).
The function will call itself (level 3) with null (E left).
The function will return to level 2.
The function will print out 99 from E.
The function will call itself (level 3) with null (E right).
The function will return to level 2.
The function will return to level 1.
The function will return to level 0.
The function will return to you.
结果是它打印出序列DBACE,在排序树中,它是按排序顺序排列的元素(11, 14, 26, 84, 99)。
如果您懒得通读我上面的大量解释,或者更简单的版本:
A26 Level 0
|
+------+------+
| |
B14 === Level 1
|
+--+--+
| |
=== === Level 2
You call the function (level 0) with A.
The function will call itself (level 1) with B (A left).
The function will call itself (level 2) with null (B left).
The function will return to level 1.
The function will print out 14 from B.
The function will call itself (level 2) with null (B right).
The function will return to level 1.
The function will return to level 0.
The function will print out 26 from A.
The function will call itself (level 1) with null (A right).
The function will return to level 0.
The function will return to you.
在这种情况下,您会得到BA 或(14,26)。