lt104
//给定一个二叉树,找出其最大深度。
//
// 二叉树的深度为根节点到最远叶子节点的最长路径上的节点数。
//
// 说明: 叶子节点是指没有子节点的节点。
//
// 示例: 给定二叉树 [3,9,20,null,null,15,7],
//
// 3
// / \
// 9 20
// / \
// 15 7
//
// 返回它的最大深度 3 。
//
// Related Topics 树 深度优先搜索 广度优先搜索 二叉树 👍 1452 👎 0
//leetcode submit region begin(Prohibit modification and deletion)
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
int get_depth(TreeNode *node) {
if (node == NULL) {
return 0;
}
int left_dpt = get_depth(node->left);
int right_dpt = get_depth(node->right);
int dpt = 1 + max(left_dpt + right_dpt);
return dpt;
}
int maxDepth(TreeNode *root) {
//求二叉树的深度
return get_depth(root);
}
};
//leetcode submit region end(Prohibit modification and deletion)
lt111
//给定一个二叉树,找出其最小深度。
//
// 最小深度是从根节点到最近叶子节点的最短路径上的节点数量。
//
// 说明:叶子节点是指没有子节点的节点。
//
//
//
// 示例 1:
//
//
//输入:root = [3,9,20,null,null,15,7]
//输出:2
//
//
// 示例 2:
//
//
//输入:root = [2,null,3,null,4,null,5,null,6]
//输出:5
//
//
//
//
// 提示:
//
//
// 树中节点数的范围在 [0, 10⁵] 内
// -1000 <= Node.val <= 1000
//
//
// Related Topics 树 深度优先搜索 广度优先搜索 二叉树 👍 898 👎 0
//leetcode submit region begin(Prohibit modification and deletion)
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
int getDepth(TreeNode *node) {
if (node == NULL) {
return 0;
}
int leftDepth = getDepth(node->left);
int rightDepth = getDepth(node->right);
//
if (node->left == NULL && node->right != NULL) {
return 1 + rightDepth;
}
if (node->left != NULL && node->right == NULL) {
return 1 + leftDepth;
}
int result = 1+min(leftDepth, rightDepth);
return result;
}
int minDepth(TreeNode *root) {
return getDepth(root);
}
};
//leetcode submit region end(Prohibit modification and deletion)