一道简单的求二叉树的最大深度,还wrong了一次,没有考虑input为NULL的情况。。。
附上code:
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
int maxDepth(TreeNode *root) {
// IMPORTANT: Please reset any member data you declared, as
// the same Solution instance will be reused for each test case.
if(!root)
return 0;
if(!root->left && !root->right)
return 1;
int left = 0, right = 0;
if(root->left)
left = maxDepth(root->left) + 1;
if(root->right)
right = maxDepth(root->right) + 1;
if(left > right)
return left;
else
return right;
}
};
LeetCode OJ上的第一题,算是水过吧。。。不知道能坚持做几道题,就当闲暇时练手吧。。。