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.
这是个很简单的题目,只需对树进行深度遍历即可,如果某个节点的深度大于最大深度,则将最大深度的值改为这个深度
遍历结束后,这个最大深度即为所求值
/** * 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: void depthFirstSearch(TreeNode* root,int len) { if (!root)return; depthFirstSearch(root->left, len + 1); depthFirstSearch(root->right, len + 1); if (maxD < len+1)maxD = len+1; } int maxDepth(TreeNode* root) { depthFirstSearch(root, 0); return maxD; } private: size_t maxD=0; };