この再帰アルゴリズムがどのように機能するかを説明します。
height(10) = max(height(5), height(30)) + 1
height(30) = max(height(28), height(42)) + 1
height(42) = 0 (no children)
height(28) = 0 (no children)
height(5) = max(height(4), height(8)) + 1
height(4) = 0 (no children)
height(8) = 0 (no children)
したがって、 を計算したい場合height(10)
は、再帰を下に展開し、結果を逆に置き換える必要があります。
height(5) = max(0, 0) + 1
height(30) = max(0, 0) + 1
height(10) = max(1, 1) + 1
height(10) = 2
編集:
コメントに記載されているように:
したがって、空のノードの高さが -1 に等しいという仮定が必要です。つまり:
height of binary tree = number of layers - 1
height(empty) = -1
また
height(null) = -1
こちらです
height(42) = max(height(null), height(null)) + 1
height(42) = max(-1, -1) + 1
height(42) = -1 + 1
height(42) = 0
上記の計算を修正しました。