Recursive and iterative solution in C++,easy to uns understand


  • 1
    V

    Solution (1): Recursion

    class Solution {
    public:
        int maxDepth(TreeNode* root) {
            int ltree = 0, rtree = 0;
            
            if (root == NULL) return 0;
            ltree = maxDepth(root->left);
            rtree = maxDepth(root->right);
            if (ltree < rtree) 
                ltree = rtree;;
                
            return ltree + 1;
        }
    };
    

    Solution (2):count the layers

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

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.