Maximum Depth of Binary Tree - LeetCode
解法一:递归,当前深度与最大深度相比,是否大于,大于就更新。
/**
* 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 dfs(int dep,int& max,TreeNode* node)
{
if(dep > max) max = dep;
if(node->left) max = dfs(dep+1,max,node->left);
if(node->right) max = dfs(dep+1,max,node->right);
return max;
}
int maxDepth(TreeNode* root) {
if(!root) return 0;
int dep = 1;
int max = 1;
return dfs(dep,max,root);
}
};
if(!root)
这种语句的时候一定要清楚的认识到root是NULL才会为真。Maximum Depth of Binary Tree - LeetCode
原文:https://www.cnblogs.com/multhree/p/10534474.html