所有的LeetCode題解索引,可以看這篇文章——【算法和數(shù)據(jù)結(jié)構(gòu)】LeetCode題解。
一、題目
二、解法
??思路分析:本題通過計算根節(jié)點到葉子節(jié)點路徑上節(jié)點的值之和,然后再對比目標(biāo)值。利用文章【算法和數(shù)據(jù)結(jié)構(gòu)】257、LeetCode二叉樹的所有路徑中的遞歸算法。這里要注意,默認(rèn)路徑之和是不等于目標(biāo)值,一旦遞歸當(dāng)中出現(xiàn)了等于的情況就直接返回,不必繼續(xù)算后面的和。因此程序當(dāng)中將結(jié)果result作為引用輸入?yún)?shù),有true出現(xiàn)就直接退出了。
??程序如下:
class Solution {
public:
void traversal(TreeNode* root, int sumOfPath, const int targetSum, bool &result) {
// 1.輸入?yún)?shù)和返回值
sumOfPath += root->val;
// 2.終止條件:遇到葉子節(jié)點
if (!root->left && !root->right) {
if (sumOfPath == targetSum) result = true;
}
// 3.單層遞歸邏輯:遞歸+回溯
if (root->left && !result) traversal(root->left, sumOfPath, targetSum, result); // 左
if (root->right && !result) traversal(root->right, sumOfPath, targetSum, result); // 右
}
bool hasPathSum(TreeNode* root, int targetSum) {
bool result = false;
if(root) traversal(root, 0, targetSum, result);
return result;
}
};
復(fù)雜度分析:文章來源:http://www.zghlxwxcb.cn/news/detail-677202.html
- 時間復(fù)雜度: O ( n ) O(n) O(n)。
- 空間復(fù)雜度: O ( n ) O(n) O(n)。
三、完整代碼
# include <iostream>
# include <vector>
# include <queue>
# include <string>
# include <algorithm>
# include <stack>
using namespace std;
// 樹節(jié)點定義
struct TreeNode {
int val;
TreeNode* left;
TreeNode* right;
TreeNode() : val(0), left(nullptr), right(nullptr) {}
TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
TreeNode(int x, TreeNode* left, TreeNode* right) : val(x), left(left), right(right) {}
};
class Solution {
public:
void traversal(TreeNode* root, int sumOfPath, const int targetSum, bool &result) {
// 1.輸入?yún)?shù)和返回值
sumOfPath += root->val;
// 2.終止條件:遇到葉子節(jié)點
if (!root->left && !root->right) {
if (sumOfPath == targetSum) result = true;
}
// 3.單層遞歸邏輯:遞歸+回溯
if (root->left && !result) traversal(root->left, sumOfPath, targetSum, result); // 左
if (root->right && !result) traversal(root->right, sumOfPath, targetSum, result); // 右
}
bool hasPathSum(TreeNode* root, int targetSum) {
bool result = false;
if(root) traversal(root, 0, targetSum, result);
return result;
}
};
template<typename T>
void my_print(T& v, const string msg)
{
cout << msg << endl;
for (class T::iterator it = v.begin(); it != v.end(); it++) {
cout << *it << ' ';
}
cout << endl;
}
template<class T1, class T2>
void my_print2(T1& v, const string str) {
cout << str << endl;
for (class T1::iterator vit = v.begin(); vit < v.end(); ++vit) {
for (class T2::iterator it = (*vit).begin(); it < (*vit).end(); ++it) {
cout << *it << ' ';
}
cout << endl;
}
}
// 前序遍歷迭代法創(chuàng)建二叉樹,每次迭代將容器首元素彈出(彈出代碼還可以再優(yōu)化)
void Tree_Generator(vector<string>& t, TreeNode*& node) {
if (!t.size() || t[0] == "NULL") return; // 退出條件
else {
node = new TreeNode(stoi(t[0].c_str())); // 中
if (t.size()) {
t.assign(t.begin() + 1, t.end());
Tree_Generator(t, node->left); // 左
}
if (t.size()) {
t.assign(t.begin() + 1, t.end());
Tree_Generator(t, node->right); // 右
}
}
}
// 層序遍歷
vector<vector<int>> levelOrder(TreeNode* root) {
queue<TreeNode*> que;
if (root != NULL) que.push(root);
vector<vector<int>> result;
while (!que.empty()) {
int size = que.size(); // size必須固定, que.size()是不斷變化的
vector<int> vec;
for (int i = 0; i < size; ++i) {
TreeNode* node = que.front();
que.pop();
vec.push_back(node->val);
if (node->left) que.push(node->left);
if (node->right) que.push(node->right);
}
result.push_back(vec);
}
return result;
}
// 二叉樹所有路徑
class Solution2 {
public:
// 前序遍歷遞歸法:精簡版本
void traversal(TreeNode* root, string path, vector<string>& result) { // 1.輸入?yún)?shù)和返回值
path += to_string(root->val); // 中間節(jié)點先加入path
if (!root->left && !root->right) { // 2.終止條件:遇到葉子節(jié)點
result.push_back(path);
return;
}
// 3.單層遞歸邏輯:遞歸+回溯
if (root->left) traversal(root->left, path + "->", result); // 左
if (root->right) traversal(root->right, path + "->", result); // 右
}
vector<string> binaryTreePaths(TreeNode* root) {
vector<string> result;
if (!root) return result;
traversal(root, "", result);
return result;
}
};
int main()
{
vector<string> t = { "5", "4", "11", "7", "NULL", "NULL", "2", "NULL", "NULL", "NULL", "8", "13", "NULL", "NULL", "4", "NULL", "1", "NULL", "NULL"}; // 前序遍歷
my_print(t, "目標(biāo)樹");
TreeNode* root = new TreeNode();
Tree_Generator(t, root);
vector<vector<int>> tree = levelOrder(root);
my_print2<vector<vector<int>>, vector<int>>(tree, "目標(biāo)樹:");
Solution2 s2;
vector<string> path = s2.binaryTreePaths(root);
my_print(path, "所有路徑為:");
Solution s;
int targetSum = 22;
bool result = s.hasPathSum(root, targetSum);
cout << "路徑總和是否滿足目標(biāo)值: " << result << endl;
system("pause");
return 0;
}
end文章來源地址http://www.zghlxwxcb.cn/news/detail-677202.html
到了這里,關(guān)于【算法與數(shù)據(jù)結(jié)構(gòu)】112、LeetCode路徑總和的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!