【二叉树】二叉树的最大深度

思路1:递归解决

1.结束条件:传入的结点为NULL

2.递归查找左子树的深度和右子树的深度

3.判断哪个较大,返回较大值+1

int maxDepth(struct TreeNode* root){
    if(!root)
        return 0;
    int left = maxDepth(root->left);
    int right = maxDepth(root->right);
    return left > right ? left+1 : right+1;
}

解题思路2:迭代层序遍历(用栈解决)

1.将根结点入栈,创建一个int值depth

2.若栈中有元素时循环:

1.出栈栈中所有结点,将他们放入一个数组

2.depth+1

3.如果这些结点有结点有左右孩子,将他们左右孩子放入栈中

3.返回depth

int maxDepth(struct TreeNode* root){
    int depth = 0;
    if(!root)
        return depth;

    struct TreeNode* stack[1024];
    int stack_top = 0;
    stack[stack_top++] = root;

    while(stack_top) {
        depth++;
        struct TreeNode* arr[1024] = { 0 };
        
        int i = 0;
        for(i = 0; stack_top;i++) {
            arr[i] = stack[--stack_top];
        }
        for(i--; i >= 0;i--) {
            if(arr[i]->right)
                stack[stack_top++] = arr[i]->right;
            if(arr[i]->left)
                stack[stack_top++] = arr[i]->left;
        }
    }

    return depth;
}

可改进:用队列解决