Code & Func
2017-11-11

第46天。

今天出游,挑到水题Maximum Depth of Binary Tree:

Given a binary tree, find its maximum depth.

The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.

说是水题,就不讲怎么做了,直接上代码吧:

1
int maxDepth(TreeNode* root) {
2
return maxDepth(root,0);
3
}
4
int maxDepth(TreeNode *root,int depth) {
5
if (root == nullptr) return depth;
6
return max(maxDepth(root->left,depth+1),maxDepth(root->right,depth+1));
7
}

恩,突然发现好像没必要写的那么长:

1
int maxDepth(TreeNode *root) {
2
if (root == nullptr) return 0;
3
return max(maxDepth(root->left),maxDepth(root->right))+1;
4
}

恩,送上一个dicuss中BFS的解法:

1
int maxDepth(TreeNode *root)
2
{
3
if(root == NULL)
4
return 0;
5
6
int res = 0;
7
queue<TreeNode *> q;
8
q.push(root);
9
while(!q.empty())
10
{
11
++ res;
12
for(int i = 0, n = q.size(); i < n; ++ i)
13
{
14
TreeNode *p = q.front();
15
q.pop();
10 collapsed lines
16
17
if(p -> left != NULL)
18
q.push(p -> left);
19
if(p -> right != NULL)
20
q.push(p -> right);
21
}
22
}
23
24
return res;
25
}
上一条动态