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

时间:2021-02-06 17:29:35

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.

求二叉树的最大深度。最大深度就是最长路径的节点数。

解法1: DFS

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

Java:DFS

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;
}
};

  

All LeetCode Questions List 题目汇总