124. 二叉树中的最大路径和
/*** Definition for a binary tree node.* 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:int ans = -1001;int dfs(TreeNode* root,int& ans) {if(!root)return 0;int l_val = dfs(root->left,ans);int r_val = dfs(root->right,ans);ans = max(ans,l_val+r_val+root->val);return max(max(l_val,r_val)+root->val,0);}int maxPathSum(TreeNode* root) {dfs(root,ans);return ans;}
};
437. 路径总和 III
/*** Definition for a binary tree node.* 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:int ans=0;unordered_map<long long, int> cnt{{0,1}};void backtracking(TreeNode* node, long long s, int targetSum) {if(!node) {return;}s+=node->val;ans += cnt.contains(s-targetSum) ? cnt[s-targetSum] : 0;cnt[s]++;backtracking(node->left,s,targetSum);backtracking(node->right,s,targetSum);cnt[s]--;}int pathSum(TreeNode* root, int targetSum) {backtracking(root,0,targetSum);return ans;}
};
199. 二叉树的右视图
/*** Definition for a binary tree node.* 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:vector<int> res;void dfs(TreeNode* node,int depth) {if(!node) {return;}if(depth==res.size())res.push_back(node->val);dfs(node->right,depth+1);dfs(node->left,depth+1);}vector<int> rightSideView(TreeNode* root) {dfs(root,0);return res;}
};