剑指Offer——(38)二叉树的深度

题目描述:

输入一棵二叉树,求该树的深度。从根结点到叶结点依次经过的结点(含根、叶结点)形成树的一条路径,最长路径的长度为树的深度。

实现如下:

//这代码真没有什么要说的。。。
//本题就是树的遍历的应用
//最长路径的长度为树的深度,所以当节点的左子树深度和右子树深度中的最大值求得后,加1即就是此节点的深度
class Solution 
{
public:
    int TreeDepth(TreeNode* pRoot)
    {
        if (pRoot == NULL) return 0;//防御性动作
        int leftChildDepth = TreeDepth(pRoot->left);//求左子树深度
        int rightChildDepth = TreeDepth(pRoot->right);//求右子树深度
        //求当前节点的深度
        return (leftChildDepth > rightChildDepth) ? (leftChildDepth + 1) : (rightChildDepth + 1);
    }
};

猜你喜欢

转载自blog.csdn.net/kongkongkkk/article/details/76006514