先遍历二叉树的左子树的深度,然后再遍历二叉树右子树的深度。最后判断左子树和右子树的深度,如果左子树比右子树深则返回左子树深度+1,否则返回右子树深度+1。
/**
* 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) {
int i ,j;
if(root == NULL)
return 0;
if(root->left != NULL)
i = maxDepth(root->left);
else
i = 0;
if(root->right != NULL)
j = maxDepth(root->right);
else
j = 0;
return i > j? i + 1 : j + 1;
}
};
“+1”的原因是根节点也算深度。