带你快速刷完67道剑指offer

No38、二叉树的深度

牛客网原题链接

题目描述

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

示例1

输入

{1,2,3,4,5,#,6,#,#,7}

返回值

4

1、BFS,迭代版本

int TreeDepth(TreeNode* pRoot)
{
    if (pRoot == nullptr) return 0;
    queue<pair<TreeNode*, int>> q;
    q.push(make_pair(pRoot, 1));
    int maxDept = 1;
    while (!q.empty()) {
        TreeNode* curNode = q.front().first;
        int curDepth = q.front().second;
        q.pop();
        if (curNode) {
            maxDept = max(maxDept, curDepth);
            q.push({ curNode->left,curDepth + 1 });
            q.push({ curNode->right,curDepth + 1 });
        }
    }
    return maxDept;
}

2、递归法

int TreeDepth(TreeNode* pRoot)
{
    if (pRoot == nullptr) return 0;
    int leftDept = TreeDepth(pRoot->left) + 1, rightDept = TreeDepth(pRoot->right) + 1;
    return max(leftDept, rightDept;
}

二刷:

1、很简单的递归方法

运行时间:2ms 占用内存:504k

int TreeDepth(TreeNode* pRoot)
{    
    if(pRoot == nullptr) return 0;
    int leftDepth = TreeDepth(pRoot->left);
    int rightDepth = TreeDepth(pRoot->right);
    return 1 + max(leftDepth,rightDepth);
}