分析
加1是因为首先进来,需要先加一层,这一层是根节点也可以理解是上一层的高度计数
这种是递归方式
class MyClass
{
public:
int maxDepth(TreeNode* root) {
if (!root){
return 0;
}
int leftDepth = maxDepth(root->left);
int rightDepth = maxDepth(root->right);
return max(leftDepth, rightDepth) + 1;
}
};
下面这种是非递归方式
int maxDepthUnrecrusion(TreeNode* root) {
if (!root){
return 0;
}
queue<TreeNode*> st;
int level = 0;
st.push(root);
while (!st.empty()){
int len = st.size();
++level;
for (int i = 0; i < len; ++i){
TreeNode* tmp = st.front();
st.pop();
if (tmp->left){
st.push(tmp->left);
}
if (tmp->right){
st.push(tmp->right);
}
}
}
return level;
}