struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
class Solution {
//I think we can use the TreeNode.val to keep the depth, and use BFS.
//It can be pretty straightforward. The last processed tree node contains the max depth.
public:
int BFS(TreeNode* root)
{
if(!root)
return 0;
else root->val = 1;
queue<TreeNode*> q;
q.push(root);
while(!q.empty())
{
TreeNode* curNode = q.front();
q.pop();
if(q.empty() && !curNode->left && !curNode->right)
return curNode->val;
if(curNode->left)
{
curNode->left->val = curNode->val+1;
q.push(curNode->left);
}
if(curNode->right)
{
curNode->right->val = curNode->val+1;
q.push(curNode->right);
}
}
}
int maxDepth(TreeNode *root) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
return BFS(root);
}
};
second time
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
int maxDepth(TreeNode *root) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
if(root == NULL) return 0;
return max(maxDepth(root->left), maxDepth(root->right))+1;
}
};