[LeetCode] 104. Maximum Depth of Binary Tree 二叉树的最大深度

2021年09月15日 阅读数:1
这篇文章主要向大家介绍[LeetCode] 104. Maximum Depth of Binary Tree 二叉树的最大深度,主要内容包括基础应用、实用技巧、原理机制等方面,希望对大家有所帮助。

Given a binary tree, find its maximum depth.html

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

Note: A leaf is a node with no children.node

Example:python

Given binary tree [3,9,20,null,null,15,7],post

    3
   / \
  9  20
    /  \
   15   7

return its depth = 3.url

求二叉树的最大深度。最大深度就是从根节点到叶节点的最长路径。code

解法1: DFShtm

解法2: 层序遍历,总层数就是最大深度。blog

Java:DFSget

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

Java: Level Travesal

public class Solution {
    public int maxDepth(TreeNode root) {
        if (root == null) return 0;
        int res = 0;
        Queue<TreeNode> q = new LinkedList<>();
        q.offer(root);
        while (!q.isEmpty()) {
            ++res;
            int n = q.size();
            for (int i = 0; i < n; ++i) {
                TreeNode t = q.poll();
                if (t.left != null) q.offer(t.left);
                if (t.right != null) q.offer(t.right);
            }
        }
        return res;
    }
}

Python: DFS

class Solution:
    # @param root, a tree node
    # @return an integer
    def maxDepth(self, root):
        if root is None:
            return 0
        else:    
            return max(self.maxDepth(root.left), self.maxDepth(root.right)) + 1

C++: DFS

class Solution {
public:
    int maxDepth(TreeNode* root) {
        if (!root) return 0;
        return 1 + max(maxDepth(root->left), maxDepth(root->right));
    }
};

C++:

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

 

相似题目:

[LeetCode] 366. Find Leaves of Binary Tree 找二叉树的叶节点

[LeetCode] 310. Minimum Height Trees 最小高度树

[LeetCode] 545. Boundary of Binary Tree 二叉树的边界

 

All LeetCode Questions List 题目汇总