求经过根节点的最大路径和,并返回每个节点值
Leetcode
给定一颗二叉树,每个节点有权重(有正有负),从根节点出发,每次只能往左子树或则右子树,求能走出来的权重最大的路径权重和,并返回该路径上每个node的指针。
注:由于返回指针不直观,这里返回 node 的值
结果
#include<iostream> #include<math.h> #include <stdlib.h> #include <algorithm> #include <vector> typedef struct node { node* left; node* right; int val; }node; int sumVecs(std::vector<int>& vecs) { int sums = 0; for (int i = 0; i < vecs.size(); i++) { sums += vecs[i]; } return sums; } /* * 递归执行最大值搜索 * 建立两个列表,一个用于存访当前搜索的路径,一个用于存访最大路径 */ std::vector<int>tempSearch; std::vector<int>maxList; int maxPath(node* tr, std::vector<int>& tempSearch, std::vector<int>& maxList) { /*当前节点为空,返回 0*/ if (tr == nullptr) { return 0; } int left = -1, right = -1; /* 将当前节点保存到当前搜索列表中 */ tempSearch.push_back(tr->val); /* 搜索当前节点的左右子树,并返回左右子树的最大路径和 */ left = maxPath(tr->left, tempSearch, maxList); right = maxPath(tr->right, tempSearch, maxList); /* 如果左子树的最大路径和大于右子树的最大路径和,且路径和大于 0,因为要求最大路径和,因此,我们只关注大于 0 的值*/ if (left > right && left > 0) { /* 当前节点已经完成搜索,向上返回父节点 */ tempSearch.pop_back(); } else if (right >= left && right > 0) { /* 当前节点已经完成搜索,向上返回父节点 */ tempSearch.pop_back(); } else { /* 已经搜索到叶子节点,判断一下当前搜索路径和最大路径,哪个路径和最大,如果搜索路径大,那么更新最大路径列表 */ if (sumVecs(tempSearch) > sumVecs(maxList)) { maxList.clear(); for (int i = 0; i < tempSearch.size(); i++) { maxList.push_back(tempSearch[i]); } } /* 叶子节点处理完毕,向上返回父节点 */ tempSearch.pop_back(); } /* 找出当前节点的最大路径和 */ int maxValue = tr->val + std::max(0, std::max(left, right)); return maxValue; } /* * 10 * 9 -20 * 1 8000 100 50000 * null null null null -2000 null null null */ int main() { node root; node a, b, c, d, e, f, g; a.val = 9; b.val = -20; c.val = 1; d.val = 8000; e.val = 10000; f.val = 500; g.val = 2000; root.val = 10; g.left = nullptr; g.right = nullptr; e.right = nullptr; e.left = &g; f.left = nullptr; f.right = nullptr; b.left = &e; b.right = &f; c.left = nullptr; c.right = nullptr; d.left = nullptr; d.right = nullptr; a.left = &c; a.right = &d; root.left = &a; root.right = &b; int value = maxPath(&root, tempSearch, maxList); std::cout << "max value " << value << std::endl; std::cout << "path " << std::endl; for (int i = 0; i < maxList.size() - 1; i++) { std::cout << maxList[i] << ", "; } std::cout << maxList[maxList.size() - 1] << std::endl; return 0; }