- 二叉树中的最大路径和
- 二叉树的最近公共祖先
分两个阶段考虑,一个是到当前节点为止,也就是以当前节点为顶节点;再一个就是从当前节点接着往上传递。
/**
* 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 max_sum = INT_MIN;
int maxPathSum(TreeNode* root) {
reverse(root);
return max_sum;
}
int reverse(TreeNode* root) {
if (root == nullptr) {
return 0;
}
int l_sum = max(0, reverse(root->left));
int r_sum = max(0, reverse(root->right));
//判断以当前节点为顶节点的最大路径和,并尝试更新全局变量
max_sum = max(max_sum, root->val+l_sum+r_sum);
//将当前节点作为中间节点往上传,此时要取消当前节点同时连接左右两棵树的情况
//要么传单独左,要么传单独右
return root->val + max(l_sum, r_sum);
}
};
二叉树的最近公共祖先
依然是分左右子树,分别判断是否有pq存在,判断依据是返回的指针是否为空
/**
* 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:
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
if (root == NULL || root == p || root == q) {
return root;
}
TreeNode* l_root = lowestCommonAncestor(root->left, p, q);
TreeNode* r_root = lowestCommonAncestor(root->right, p, q);
if (l_root && r_root) {
return root;
}
else {
if (l_root) {
return l_root;
}
else {
return r_root;
}
}
}
};
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)