Leetcode 104. Maximum Depth of Binary Tree

Posted zhangwj0101

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Leetcode 104. Maximum Depth of Binary Tree相关的知识,希望对你有一定的参考价值。

Question

Given a binary tree, find its maximum depth.

The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.

Code

递归方式

 /**
     * 递归的方式
     *
     * @param root
     * @return
     */
    public int maxDepth(TreeNode root) 
        if (root == null) 
            return 0;
        
        return Math.max(maxDepth(root.left), maxDepth(root.right)) + 1;
    

队列的方式

 /**
     * 队列的方式
     *
     * @param root
     * @return
     */
    public int maxDepth1(TreeNode root) 
        if (root == null) 
            return 0;
        
        Queue<TreeNode> queues = new LinkedList<>();
        queues.add(root);
        int level = 0;
        while (!queues.isEmpty()) 
            int len = queues.size();
            level++;
            for (int i = 0; i < len; i++) 
                TreeNode t = queues.poll();
                if (t.left != null) 
                    queues.offer(t.left);
                
                if (t.right != null) 
                    queues.offer(t.right);
                
            
        
        return level;
    

以上是关于Leetcode 104. Maximum Depth of Binary Tree的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode104. Maximum Depth of Binary Tree

leetcode104-Maximum Depth of Binary Tree

Leetcode刷题记录[python]——104 Maximum Depth of Binary Tree

LeetCode 104. Maximum Depth of Binary Tree

[Lintcode]97. Maximum Depth of Binary Tree/[Leetcode]104. Maximum Depth of Binary Tree

LeetCode 104 Maximum Depth of Binary Tree