从任意两个节点之间最大的一条路径...
/** * Definition for binary tree * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: int ans; int search(TreeNode* root){ if(root == nullptr) return 0; int left , right; left = INT_MIN; right = INT_MIN; //node if(root -> left == nullptr && root -> right == nullptr){ if(root -> val > ans){ ans = root -> val; return root -> val; } } //left bool hasLeft = false; bool hasRight = false; if(root -> left != nullptr){ left = search(root -> left); hasLeft = true; } //right if(root -> right != nullptr){ right = search(root -> right); hasRight = true; } if(hasLeft && hasRight){ if(left + right + root->val > ans){ ans = left + right + root -> val; } } if(hasLeft){ if(left + root -> val > ans){ ans = left + root -> val; } } if(hasRight){ if(right + root -> val > ans){ ans = right + root -> val; } } if(root -> val > ans) ans = root -> val; int res = INT_MIN; if(hasLeft){ res = left + root -> val; } if(hasRight){ res = max(res , right + root -> val); } res = max(res , root -> val); return res; } int maxPathSum(TreeNode *root) { if(root == nullptr) return 0; //left + right + root -> ans //left + root -> go on //right + root -> go on //root -> go on ans = INT_MIN; search(root); return ans; } };
by 1957