二叉树OJ(三)543. 二叉树的直径 124. 二叉树中的最大路径和 困难
543. 二叉树的直径
在二叉树的最大深度基础上维护一个res,每次访问一个结点时,维护一个左右字数深度之和的最大值()
class Solution {
public:int res = 0;int dfs(TreeNode* root){if(root == nullptr)return 0;int left = dfs(root->left);int right = dfs(root->right);res = max(res, left + right);// return left > right ? left+1 : right+1;return max(left, right)+1;}int diameterOfBinaryTree(TreeNode* root) {dfs(root);return res;}
};
124. 二叉树中的最大路径和
二叉树中的 路径 被定义为一条节点序列,序列中每对相邻节点之间都存在一条边。同一个节点在一条路径序列中 至多出现一次 。该路径 至少包含一个 节点,且不一定经过根节点。
路径和 是路径中各节点值的总和。
给你一个二叉树的根节点 root
,返回其 最大路径和 。
class Solution {
public:int res = INT_MIN;int dfs(TreeNode* root){if(root == nullptr)return 0;int left = dfs(root->left);int right = dfs(root->right);res = max(res, left + right+root->val);return max(max(left, right)+root->val ,0);}int maxPathSum(TreeNode* root) {dfs(root);return res;}
};
面向结果编程:
class Solution {
public:int res = INT_MIN; 用来维护最大值int dfs(TreeNode* root){if(root == nullptr)return 0;int left = dfs(root->left);int right = dfs(root->right);// 维护最大值res = max(res, left + right + root->val);res = max(res, root->val);res = max(res, left+root->val);res = max(res, right+root->val);// 返回单支树中最优路径和int r1 = root->val;int r2 = left+root->val;int r3 = right+root->val;int mx = max(max(r1, r2), r3);return mx;}int maxPathSum(TreeNode* root) {dfs(root);return res;}
};