9.14 DFS 简单 111 Minimum Depth of Binary Tree 112 Path Sum
111. Minimum Depth of Binary Tree【默写】
class Solution {
public:int DFS(TreeNode* node) {if(!node) {return INT_MAX; // 如果当前节点是空的,返回一个很大的值,因为空节点不能作为叶子节点}if(!node->left && !node->right) {return 1; // 当前节点是叶子节点,返回深度1}int lh = DFS(node->left); // 递归左子树int rh = DFS(node->right); // 递归右子树return min(lh, rh) + 1; // 返回左右子树的较小深度并加1}int minDepth(TreeNode* root) {if (!root) return 0; // 特殊情况处理,根节点为空时,深度为0return DFS(root);}
};
112. Path Sum
class Solution {
public:bool DFS(TreeNode* node, int targetSum, int sum) {if (!node) {return false; // 空节点,返回false}sum += node->val; // 累加当前节点的值// 如果是叶子节点,检查当前路径的和是否等于targetSumif (!node->left && !node->right) {return sum == targetSum;}// 递归检查左子树和右子树return DFS(node->left, targetSum, sum) || DFS(node->right, targetSum, sum);}bool hasPathSum(TreeNode* root, int targetSum) {// 初始路径和是0return DFS(root, targetSum, 0);}
};