解法一 recursion
divide and conquer
class Solution {
public:
int maxDepth(TreeNode * root) {
if(!root) return 0;
int left = maxDepth(root->left);
int right = maxDepth(root->right);
return max(left, right)+1;
}
};
traverse
class Solution {
public:
int res;
int maxDepth(TreeNode * root) {
res=0;
helper(root, 0);
return res;
}
void helper(TreeNode* root, int temp){
res = max(temp, res);
if(!root) return;
helper(root->left, temp+1);
helper(root->right, temp+1);
}
};
解法二 non-recursion
class Solution {
public:
int maxDepth(TreeNode * root) {\
int res=0;
queue<TreeNode*> st;
if(!root) return res;
st.push(root);
while(!st.empty()){
int n = st.size();
for(int i=0;i<n;i++){
TreeNode* t = st.front(); st.pop();
if(t->right) st.push(t->right);
if(t->left) st.push(t->left);
}
res++;
}
return res;
}
};