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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| /** * 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) { if(root == NULL) return 0; return max(1+maxDepth(root->left),1+maxDepth(root->right)); } };
|
这道题目就是不断的递归左右子树,父的深度比儿子深度大1,左右儿子深度做比较,得出最大深度。
可以看出递归思想在解决树问题的重要性。