The maximum depth of the binary tree p16 (leetcode 104)

A: problem-solving ideas

This question can be recursive and iterative methods to solve.

Two: Complete code examples (C ++ version and the Java version)

Recursion C ++:

class Solution 
{
public:
    int max(int a, int b)
    {
        return a > b ? a : b;
    }

    int maxDepth(TreeNode* root) 
    {
        if (root == NULL) return 0;

        return max(maxDepth(root->left),maxDepth(root->right))+1;
    }
};

Recursion Java:

class Solution {
    public int maxDepth(TreeNode root) 
    {
           if(root==null) return 0;
           
           return Math.max(maxDepth(root.left),maxDepth(root.right))+1;
    }
}

Iterative Methods C ++:

//Time:O(n),Space:O(n)
class Solution 
{
public:
    int maxDepth(TreeNode* root) 
    {
        if (root == NULL) return 0;

        queue<TreeNode*> queue;
        queue.push(root);

        int depth = 0;

        while (!queue.empty())
        {
            int size = queue.size();

            for (int i = 0; i < size; i++)
            {
                TreeNode* t = queue.front();
                queue.pop();

                if (t->left != NULL) queue.push(t->left);
                if (t->right != NULL) queue.push(t->right);
            }

            depth++;
        }

        return depth;
    }
};

Iterative method Java:

class Solution {
    public int maxDepth(TreeNode root)
    {
           if(root==null) return 0;
           Queue<TreeNode> queue=new LinkedList<>();
           int depth=0;

           queue.add(root);

           while(!queue.isEmpty())
           {
               int size=queue.size();

               for(int i=0;i<size;i++)
               {
                   TreeNode t=queue.poll();
                   
                   if(t.left!=null) queue.add(t.left);
                   if(t.right!=null) queue.add(t.right);
               }

               depth++;
           }

           return depth;
    }
}

 

Guess you like

Origin www.cnblogs.com/repinkply/p/12455739.html