这是一个递归函数(反复调用自己的函数)。 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)
。
或者在下一行生成空指针异常。 – Don 2010-01-11 05:03:59
好点,@Don,你几乎肯定会在堆栈溢出之前得到一个空指针异常(除非你的堆栈特别小)。修改来修复。 – paxdiablo 2010-01-11 05:54:11
对于一个全面的,很好解释的答案+1。 – Matt 2010-01-11 10:27:14