NC13 二叉树的最大深度
二叉树的最大深度
https://www.nowcoder.com/practice/8a2b2bf6c19b4f23a9bdb9b233eefa73?tpId=196&&tqId=37055&rp=1&ru=/ta/job-code-total&qru=/ta/job-code-total/question-ranking
题目: 简单题
给定一个二叉树,找出其最大深度。
示例:略
思路:
本题较为简单,使用递归即可解决。如果节点为空,则高度为0,否则开始递归,返回值时需要进行+1,否则返回值不会变化。
代码:
/**
*
* @param root TreeNode类
* @return int整型
*/
public int maxDepth (TreeNode root) {
// write code here
if (root == null) {
return 0;
} else {
int leftHeight = maxDepth(root.left);
int rightHeight = maxDepth(root.right);
return Math.max(leftHeight, rightHeight) + 1;
}
}
}