一行递归代码

二叉树的深度

http://www.nowcoder.com/questionTerminal/435fb86331474282a3499955f0a41e8b

int TreeDepth(TreeNode* pRoot)
    {
        return pRoot ? max(TreeDepth(pRoot->left),TreeDepth(pRoot->right))+1:0;
    }

终止条件: 当 pRoot 为空,说明已越过叶节点,因此返回 深度 0。
计算节点 root 的 左子树的深度 ,即调用 maxDepth(root.left);
计算节点 root 的 右子树的深度 ,即调用 maxDepth(root.right);
返回值: 返回此树的深度 ,即 max(maxDepth(pRoot->left), maxDepth(pRoot->right)) + 1

全部评论

相关推荐

点赞 评论 收藏
转发
点赞 收藏 评论
分享
牛客网
牛客企业服务