国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 學院 > 開發設計 > 正文

leetcode-112-Path Sum

2019-11-11 04:02:43
字體:
來源:轉載
供稿:網友

問題

題目:[Path Sum]

思路

下面的代碼并不是原始問題的代碼。而是改良后的問題。即求一條路徑和為sum。要求必須從根開始,但是不一定到葉子結束。 下面用到了回溯法,我覺得這題也是回溯法比較好的實現。 回溯法肯定用到了“剪枝”,但他的關鍵是要回溯到上一個狀態。

代碼

/** * 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: bool haspathSum(TreeNode* root, int sum) { if(!root) return false; int ans = 0; bool found = false; dfs( root, sum, ans, found); return found; }PRivate: void dfs(TreeNode* root, int sum, int& ret, bool& found){ if(root&&!found){ ret += root->val; if(ret == sum){ found = true; return;} else if( ret > sum ){ ret -= root->val; // backtrace return ; } else{ dfs(root->left, sum, ret, found); dfs(root->right, sum, ret, found); } } }};

或者其實你沒必要這么寫,睡了一晚上發現。這也不算回溯。就是參數傳遞的時候。不要傳遞引用了。

代碼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: bool hasPathSum(TreeNode* root, int sum) { if(!root) return false; int ans = 0; bool found = false; dfs( root, sum, ans, found); return found; }private: void dfs(TreeNode* root, int sum, int ret, bool& found){ if(root&&!found){ ret += root->val; if(ret == sum){ found = true; return;} else if( ret > sum ) return; else{ dfs(root->left, sum, ret, found); dfs(root->right, sum, ret, found); } } }};

思路(本題)

因為要訪問到最底層,所以到葉子的時候判斷一下就行了。

代碼

/** * 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: bool hasPathSum(TreeNode* root, int sum) { if(!root) return false; int ans = 0; bool found = false; dfs( root, sum, ans, found); return found; }private: void dfs(TreeNode* root, int sum, int ret, bool& found){ if(root && !found){ ret += root->val; if(!root->left && !root->right){ if(ret==sum) found = true; return; } dfs( root->left, sum, ret, found ); dfs( root->right, sum, ret, found ); } }};
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 陇川县| 横山县| 四子王旗| 庆阳市| 郎溪县| 赤峰市| 石狮市| 霍邱县| 开平市| 云梦县| 盘锦市| 宜良县| 郓城县| 沙坪坝区| 浦城县| 凤台县| 天柱县| 天气| 临沂市| 甘孜县| 房产| 龙陵县| 安多县| 扎赉特旗| 大同市| 德兴市| 繁昌县| 云龙县| 沅陵县| 枣庄市| 香格里拉县| 安顺市| 胶州市| 梅州市| 隆德县| 凌源市| 滦南县| 张北县| 沁源县| 辽宁省| 新田县|