題目
輸入一棵二叉樹的根節點,求該樹的深度。從根節點到葉節點依次經過的節點(含根、葉節點)形成樹的一條路徑,最長路徑的長度爲樹的深度。
例如:
給定二叉樹 [3,9,20,null,null,15,7],
3
/
9 20
/
15 7
返回它的最大深度 3 。
提示:
節點總數 <= 10000
代碼
Python
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
# # 法一:
# # DFS中後序遍歷,核心思想是樹的深度=max(左子樹深度,右子樹深度)+1
# # O(N),N是樹的節點數
# class Solution:
# def maxDepth(self, root: TreeNode) -> int:
# if not root: return 0
# return max(self.maxDepth(root.left), self.maxDepth(root.right))+1
# 法二:
# BFS,核心思想是遍歷一層,則計數器加1
# O(N),N是樹的節點數
class Solution:
def maxDepth(self, root: TreeNode) -> int:
if not root: return 0
Q,res=[root],0 # 初始化隊列,計數器
while Q:
tmp = [] # 臨時存儲下一層節點
for node in Q:
if node.left: tmp.append(node.left)
if node.right: tmp.append(node.right)
Q=tmp # 更新隊列
res+=1 # 計數器+1
return res
C++
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
// // 法一:DFS
// class Solution {
// public:
// int maxDepth(TreeNode* root) {
// if (root==NULL) return 0;
// return max(maxDepth(root->left),maxDepth(root->right))+1;
// }
// };
// 法二:BFS
class Solution {
public:
int maxDepth(TreeNode* root) {
if (root==NULL) return 0;
queue<TreeNode*> Q;
Q.push(root);
int res=0;
while (!Q.empty()) {
int size=Q.size();
for (int i=0; i<size; i++) {
TreeNode* node=Q.front();
Q.pop();
if (node->left) Q.push(node->left);
if (node->right) Q.push(node->right);
}
res++;
}
return res;
}
};