
原题链接
class Solution {
public:
int TreeDepth(TreeNode* root) {
// 根节点为叶子节点,返回0
if (!root)return 0;
// 先遍历左子树,再遍历右子树
int lf = TreeDepth(root->left);
int rh = TreeDepth(root->right);
// 左右子树最大值+1
return max(lf, rh) + 1;
}
};
思路:
这是一道DFS的题,主要实现是后序遍历+回溯,先遍历树的左子树,再遍历树的右子树,当根节点为叶子节点时,返回0,回溯时,取左右子树的最大值+1。
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)