题解 | #二叉树根节点到叶子节点的所有路径和#
二叉树的最大深度
http://www.nowcoder.com/practice/8a2b2bf6c19b4f23a9bdb9b233eefa73
注意要回溯两次 根节点和每一个节点被搜完后
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
class Solution {
public:
/**
*
* @param root TreeNode类
* @return int整型
*/
int ans = 0;
int cnt = 0;
void dfs(TreeNode* root){
if(root->left == NULL && root->right == NULL){
cnt++;
ans = max(cnt,ans);
cnt--;
return;
}
cnt++;
if(root->left != NULL) dfs(root->left);
if(root->right != NULL) dfs(root->right);
cnt--;
}
int maxDepth(TreeNode* root) {
if(root == NULL) return 0;
dfs(root);
return ans;
}
};