此問題可拆解爲求左右子樹最高的高度加1,遞歸出口爲訪問到葉子節點本身時其高度爲1,此時返回0即可。
class Solution{
public int height(TreeNode root){
if(root == null){
return 0;
}
return Math.max(height(root.left),height(root.right)) + 1;
}
}
由於使用了遞歸,內存開銷巨大,不過不失爲一種簡單的方法求樹高。