题目描述:
递归
class Solution { public: int maxDepth(TreeNode* root) { if(root == NULL) return 0; TreeNode *pleft = root->left; TreeNode *pright = root->right; return max(maxDepth(pleft) + 1, maxDepth(pright) + 1); } };
循环
class Solution { public: int maxDepth(TreeNode* root) { if(root == NULL) return 0; queue<TreeNode *> qu; int ret = 0; qu.push(root); while(!qu.empty()){ ret++; for(int i = 0,n = qu.size() ; i < n; i++){ TreeNode *tmp = qu.front(); qu.pop(); if(tmp->left != NULL) qu.push(tmp->left); if(tmp->right != NULL) qu.push(tmp->right); } } return ret; } };