LeetCode112路徑總和
阿新 • • 發佈:2020-07-25
題目連結
https://leetcode-cn.com/problems/path-sum/
題解
- 在dfs過程中要記錄當前節點與根節點之間的距離,並且回溯時也需要更新該值
- 注意要求是葉子節點到根節點之間的距離
- 詳細思路見程式碼註釋
// Problem: LeetCode 112 // URL: https://leetcode-cn.com/problems/path-sum/ // Tags: Tree Recursion DFS 回溯 // Difficulty: Easy #include <iostream> using namespace std; struct TreeNode{ int val; TreeNode *left; TreeNode *right; TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} }; class Solution{ private: bool existed = false; // 當前是否存在葉子節點到根節點的路徑和等於給定sum int now = 0; // 當前節點的路徑和 int sum = -1; // 給定的sum void dfs(TreeNode* root){ // 如果當前已找到符合要求的節點,則不用再搜尋 if(existed==true) return ; // 如果是空節點,則不用搜索 if(root==nullptr) return ; // 遍歷當前節點,計算其到根節點之間的距離 this->now += root->val; // 如果是葉子結點並且其與根節點的距離等於給定sum,則該節點符合條件 if(root->left==nullptr && root->right==nullptr && this->now == this->sum){ existed = true; return; } // 搜尋左子樹和右子樹 dfs(root->left); dfs(root->right); // 該子樹已搜尋完畢,需要更新當前節點與根節點之間的距離(回溯) this->now -= root->val; } public: bool hasPathSum(TreeNode* root, int sum) { // 設定目標 this->sum = sum; // 深度搜索 dfs(root); // 返回搜尋結果 return this->existed; } };
作者:@臭鹹魚
轉載請註明出處:https://www.cnblogs.com/chouxianyu/
歡迎討論和交流!