日本搞逼视频_黄色一级片免费在线观看_色99久久_性明星video另类hd_欧美77_综合在线视频

國內最全IT社區平臺 聯系我們 | 收藏本站
阿里云優惠2
您當前位置:首頁 > php開源 > php教程 > [LeetCode]112.Path Sum

[LeetCode]112.Path Sum

來源:程序員人生   發布時間:2015-01-04 08:56:25 閱讀次數:2489次

【題目】

Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up all the values along the path equals the given sum.

For example:
Given the below binary tree and sum = 22,
5 / 4 8 / / 11 13 4 / 7 2 1

return true, as there exist a root-to-leaf path 5->4->11->2 which sum is 22.


【分析】

題目要求是從根節點到葉子節點的1條路徑。剛開始沒看清楚,還以為隨便路徑。

題目只要求返回true或false,因此沒有必要記錄路徑。

【代碼】

/********************************* * 日期:2015-01-01 * 作者:SJF0115 * 題目: 112.Path Sum * 來源:https://oj.leetcode.com/problems/path-sum/ * 結果:AC * 來源:LeetCode * 博客: * 時間復雜度:O(n) * 空間復雜度:O(logn) **********************************/ #include <iostream> #include <queue> #include <vector> using namespace std; // 2叉樹節點 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 == NULL){ return false; }//if // 找到1條從根節點到葉子節點的路徑 if(root->left == NULL && root->right == NULL){ return sum == root->val; }//if // 左子樹 bool left = hasPathSum(root->left,sum - root->val); // 右子樹 bool right = hasPathSum(root->right,sum - root->val); return left || right; } }; // 創建2叉樹 TreeNode* CreateTreeByLevel(vector<int> num){ int len = num.size(); if(len == 0){ return NULL; }//if queue<TreeNode*> queue; int index = 0; // 創建根節點 TreeNode *root = new TreeNode(num[index++]); // 入隊列 queue.push(root); TreeNode *p = NULL; while(!queue.empty() && index < len){ // 出隊列 p = queue.front(); queue.pop(); // 左節點 if(index < len && num[index] != ⑴){ // 如果不空創建1個節點 TreeNode *leftNode = new TreeNode(num[index]); p->left = leftNode; queue.push(leftNode); } index++; // 右節點 if(index < len && num[index] != ⑴){ // 如果不空創建1個節點 TreeNode *rightNode = new TreeNode(num[index]); p->right = rightNode; queue.push(rightNode); } index++; }//while return root; } int main() { Solution solution; // ⑴代表NULL vector<int> num = {5,4,8,11,⑴,13,4,7,2,⑴,⑴,⑴,1}; TreeNode* root = CreateTreeByLevel(num); cout<<solution.hasPathSum(root,22)<<endl; }



生活不易,碼農辛苦
如果您覺得本網站對您的學習有所幫助,可以手機掃描二維碼進行捐贈
程序員人生
------分隔線----------------------------
分享到:
------分隔線----------------------------
關閉
程序員人生
主站蜘蛛池模板: 国产又色又爽又黄又免费 | 影视在线观看 | 日韩 国产 欧美 | 欧洲一区二区 | 亚洲国产91 | 最新黄色在线视频 | 欧美在线观看网站 | 在线日韩电影 | 91网站在线看| 国产精品久久久久久久午夜片 | 欧美日韩国产综合在线 | 岛国片在线免费观看 | 精品在线一区二区三区 | 国产毛片一区二区 | 国产精品一区在线 | 免费福利av| 视频三区| 亚洲区av | 国产日韩欧美在线 | 国产99久久精品一区二区永久免费 | 中文字幕在线观看不卡 | 国产免费视频 | 在线日韩一区 | 99精品综合 | 欧美伦乱 | 成人久久久 | 精品国产一区二区三区在线观看 | 国产美女一区二区三区 | 中文精品视频 | 国产精品久久久久久久久潘金莲 | av在线电影免费观看 | 综合视频一区 | 青青草十七色 | 国产精品久久久久永久免费观看 | av麻豆 | 亚洲日本va中文字幕久久 | 欧美日韩天堂 | 美女福利视频网站 | 成人精品国产免费网站 | 亚洲成人av综合 | 99re热|