给定一个二叉树,找出其最大深度。
二叉树的深度为根节点到最远叶子节点的最长路径上的节点数。
说明: 叶子节点是指没有子节点的节点。
示例:
给定二叉树 [3,9,20,null,null,15,7],
返回它的最大深度 3 。
解题思路:
树结构的问题,一般可以用递归来实现。
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: TreeNode) -> int:
if root == None:
return 0
num_l = self.maxDepth(root.left)
num_r = self.maxDepth(root.right)
return max(num_l, num_r) + 1
C++
解法一:
使用深度优先搜索策略(DFS),通过递归求解问题。
class Solution {
public:
int maxDepth(TreeNode* root) {
if(!root) return 0;
return max(maxDepth(root->left), maxDepth(root->right))+1;
}
};
递归中包含着 动态规划 思想。使用公式表述如下:
方法二:
迭代法,使用栈遍历树中每个节点,并实时更新深度值。
/**
* 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) {
stack<pair<int, TreeNode *>> sk1;
if(root) sk1.push(make_pair(1, root));
int depth = 0;
int cur_depth;
while(!sk1.empty()){
cur_depth = sk1.top().first;
root = sk1.top().second;
sk1.pop();
if(root){
depth = max(depth, cur_depth);
sk1.push(make_pair(cur_depth+1, root->left));
sk1.push(make_pair(cur_depth+1, root->right));
}
}
return depth;
}
};