LeetCode104 find the maximum depth of the binary tree

Non-recursive code:

class Solution {
    
    
public:
    int maxDepth(TreeNode* root) {
    
    
        int depth=0;
        queue<TreeNode*> que;
        if(root!=NULL) que.push(root);
        while(!que.empty())
        {
    
    
            int size=que.size();
            for(int i=0;i<size;i++)
            {
    
    
                TreeNode* node=que.front();
                que.pop();
                if(node->left)  que.push(node->left);
                if(node->right)  que.push(node->right);  
            }
            depth++;
        }
        return depth;
    }
};

Recursive code:

    int getdepth(TreeNode* node)   
    {
    
    
        //递归终止条件
        if(node==NULL) return 0;
        //确定单次递归的逻辑
        int leftdepth=getdepth(node->left);
        int rightdepth=getdepth(node->right);
        int depth=1+max(leftdepth,rightdepth);
        return  depth;
    }
    int maxDepth(TreeNode* root) {
    
    
        return getdepth(root);
    }

Guess you like

Origin blog.csdn.net/ALITAAAA/article/details/109370178