> 文章列表 > 代码随想录_leetcode104、111迭代法

代码随想录_leetcode104、111迭代法

代码随想录_leetcode104、111迭代法

leetcode104.二叉树的最大深度

104. 二叉树的最大深度

给定一个二叉树,找出其最大深度。

二叉树的深度为根节点到最远叶子节点的最长路径上的节点数。

说明: 叶子节点是指没有子节点的节点。

示例:
给定二叉树 [3,9,20,null,null,15,7]

    3/ \\9  20/  \\15   7

返回它的最大深度 3 。

 代码

// leetcode104
// 递归
class Solution {
public:int getDepth(TreeNode* cur){if (cur == nullptr){return 0;}return 1 + max(getDepth(cur->left), getDepth(cur->right));}int maxDepth(TreeNode* root) {return getDepth(root);}
};

 leetcode111 二叉树的最小深度

111. 二叉树的最小深度

给定一个二叉树,找出其最小深度。

最小深度是从根节点到最近叶子节点的最短路径上的节点数量。

说明:叶子节点是指没有子节点的节点。

示例 1:

输入:root = [3,9,20,null,null,15,7]
输出:2

 

示例 2:

输入:root = [2,null,3,null,4,null,5,null,6]
输出:5

代码

// leetcode111
// 递归
// 最小深度找的是叶子结点
// 而叶子结点是没有左右结点的 所以和最大深度不同
class Solution {
public:int getDepth(TreeNode* cur){if (cur == nullptr){return 0;}if (cur->left == nullptr){return getDepth(cur->right) + 1;}if (cur->right == nullptr){return getDepth(cur->left) + 1;}return min(getDepth(cur->left), minDepth(cur->right)) + 1;}int minDepth(TreeNode* root) {return getDepth(root);}
};