maximum depth of binary treee

The Question

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.
Subscribe to see which companies asked this question.

The Answer

The Key

  1. 考虑到两边遍历的情况,不要两边同时操作一个变量。

代码如下

1
2
3
4
5
6
7
8
class Solution {
public:
int (TreeNode* root) {
if(!root)return NULL;
TreeNode* p=root->left;TreeNode* q=root->right;
return max(maxDepth(p),maxDepth(q))+1;
}
};

~Thanks~
By 海天游草~~~2017.3.16