Tod*_*odd 3 java binary-tree return data-structures
我对以下代码有疑问
private void printTree(Node node){
if(node==null) return;
printTree(node.left);
System.out.print(node.data+" ");
printTree(node.right);
}
Run Code Online (Sandbox Code Playgroud)
我真的不明白'回归'.那里的声明.看起来如果node为null,则代码不返回任何内容.但是如果没有那一行,编译器会生成异常错误.
pax*_*blo 16
这是一个递归函数(一个自称重复的函数).这样做的目的return
是确保它不会永远尝试这样做,导致在树的底部运行时出现空指针异常.
会发生的情况是,第一次使用节点(通常但不总是根节点)调用此函数时,它将首先打印出该节点的左子树,然后打印出节点本身的值,然后该节点的右侧子树.
打印出子树的方式是通过该子树的顶级节点调用自身.这是一种优雅处理递归结构的常用方法.
测试null
是这样的,它具有这样的条件:当树到达你正在检查的特定一侧没有子节点的节点(向左或向右)时,向下搜索树的层次.
举例来说,假设您有以下树(大写字母的数字是真实节点,数字是它们的值,===
标记是空的):
A26 Level 0
|
+------+------+
| |
B14 C84 Level 1
| |
+--+--+ +--+--+
| | | |
D11 === === E99 Level 2
| |
+--+--+ +--+--+
| | | |
=== === === === Level 3
Run Code Online (Sandbox Code Playgroud)
当你用这个函数调用函数时,会发生什么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.
Run Code Online (Sandbox Code Playgroud)
结果是它打印出的序列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.
Run Code Online (Sandbox Code Playgroud)
在那种情况下,你得到BA
或(14,26)
.