法一: 自顶向下递归
class Solution { public: int max_layer=1; int maxDepth(TreeNode* root) { if(!root)return 0; count_depth(root,0); return max_layer; } void count_depth(TreeNode *p,int cur_layer){ if(p){ cur_layer++; count_depth(p->left,cur_layer); count_depth(p->right,cur_layer); } else{ max_layer=max(max_layer,cur_layer); } } };法二自底向上,稍微难理解一点
class Solution { public: int maxDepth(TreeNode* root) { if(!root)return 0; int left_depth=maxDepth(root->left); int right_depth=maxDepth(root->right); return max(left_depth,right_depth)+1; } };法三中序非递归
class Solution { public: int maxDepth(TreeNode* root) { if(!root)return 0; stack<TreeNode*>node; stack<int>depth; int max_layer,cur_layer; max_layer=cur_layer=1; TreeNode *p=root; while(p||!node.empty()){ while(p){ node.push(p); p=p->left; depth.push(cur_layer); cur_layer++; } p=node.top(); cur_layer=depth.top(); max_layer=max(max_layer,cur_layer); depth.pop(); node.pop(); cur_layer++; p=p->right; } return max_layer; } };