p16 二叉树的最大深度 (leetcode 104)

一:解题思路

这道题可以用递归法和迭代法来解决。

二:完整代码示例 (C++版和Java版)

递归法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;
    }
};

递归法Java:

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

迭代法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;
    }
};

迭代法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;
    }
}

猜你喜欢

转载自www.cnblogs.com/repinkply/p/12455739.html