原题
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.
Note: A leaf is a node with no children.
Example:
Given binary tree [3,9,20,null,null,15,7]
,
3
/ \
9 20
/ \
15 7
return its depth = 3.
Reference Answer
思路分析
可以参考层遍历思路,只计数层数;
Reference Code
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def maxDepth(self, root):
"""
:type root: TreeNode
:rtype: int
"""
if not root:
return 0
current_layer = [root]
next_layer = []
deepth = 0
while (current_layer):
deepth += 1
for node in current_layer:
if node.left:
next_layer.append(node.left);
if node.right:
next_layer.append(node.right);
current_layer = next_layer[:]
next_layer = []
return deepth
Python优化版本:
做进一步优化,递归调用,只考虑层数即可。
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def maxDepth(self, root):
"""
:type root: TreeNode
:rtype: int
"""
if not root:
return 0
return max(self.maxDepth(root.left), self.maxDepth(root.right)) + 1
C++ 版本:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
int maxDepth(TreeNode* root) {
if (!root){
return 0;
}
int deepth = 0;
queue<TreeNode*> current_node;
// vector<TreeNode*> next_node;
current_node.push(root);
while (!current_node.empty()){
++deepth;
int pre_count = current_node.size();
for(int i=0; i < pre_count; i++){
TreeNode *node = current_node.front();
current_node.pop();
// current_node.pop();
if (node->left != NULL){
current_node.push(node->left);
}
if (node->right != NULL){
current_node.push(node->right);
}
}
}
return deepth;
}
};
C++优化版本:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
int maxDepth(TreeNode* root) {
if (!root){
return 0;
}
int left_depth = maxDepth(root->left);
int right_depth = maxDepth(root->right);
return max(left_depth, right_depth) + 1;
}
};
Note:
- 这种思路典型的递归调用,明显不用复杂地将各层节点都保存等,时间复杂度、空间复杂度都大大降低,要切记!切记!!!
参考文献:
[1] https://www.kancloud.cn/kancloud/data-structure-and-algorithm-notes/73030