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

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

leetcode-112-Path Sum

2019-11-11 02:08:34
字體:
來源:轉載
供稿:網友

問題

題目:[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 ); } }};
上一篇:JDBC

下一篇:shader學習(8)

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 林周县| 祥云县| 民乐县| 云浮市| 彩票| 邵阳县| 宣城市| 平昌县| 疏附县| 顺平县| 碌曲县| 辉南县| 威信县| 利津县| 西峡县| 邵东县| 呼玛县| 历史| 罗源县| 古浪县| 治多县| 静乐县| 福鼎市| 新巴尔虎左旗| 沙雅县| 敦化市| 拉萨市| 遵义县| 榆社县| 霸州市| 湘潭市| 清苑县| 安义县| 奎屯市| 辽阳县| 内黄县| 恭城| 泽州县| 农安县| 大关县| 甘肃省|