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
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
int maxDepth(TreeNode* root) {
return root==NULL?0:max(maxDepth(root->left),maxDepth(root->right))+1;
}
};
这个问题的解决思路就是:递归地判断左子树和右子树谁的节点深,因为每次传入的节点若为NULL,则该次迭代返回0,否则加1.