输入一棵二叉树,求该树的深度。从根结点到叶结点依次经过的结点(含根、叶结点)形成树的一条路径,最长路径的长度为树的深度。
输入
{1,2,3,4,5,#,6,#,#,7}
返回值
4
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;
}int TreeDepth(TreeNode* pRoot)
{
if (pRoot == nullptr) return 0;
int leftDept = TreeDepth(pRoot->left) + 1, rightDept = TreeDepth(pRoot->right) + 1;
return max(leftDept, rightDept;
}运行时间: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);
}