這是一個遞歸函數(反覆調用自己的函數)。 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