Given a binary tree, find the length of the longest path where each node in the path has the same value. This path may or may not pass through the root.
The length of path between two nodes is represented by the number of edges between them.
Example 1:
Input:
5 / \ 4 5 / \ \ 1 1 5
Output: 2
Example 2:
Input:
1 / \ 4 5 / \ \ 4 4 5
Output: 2
Note: The given binary tree has not more than 10000 nodes. The height of the tree is not more than 1000.
A:
*************要多写几遍, 一开始bug挺多的 ************
/** * 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 longestUnivaluePath(TreeNode* root) { if(root == nullptr) return 0; int withRootpath = 0; if(root->left != nullptr ) withRootpath += maxDepthWithValue(root->left, root->val); if(root->right != nullptr) withRootpath += maxDepthWithValue(root->right, root->val); return max(withRootpath , max(longestUnivaluePath(root->left),longestUnivaluePath(root->right))); } private: int maxDepthWithValue(TreeNode* root, const int value) { if(root ==nullptr || root->val != value) return 0; int res = 0; int ll = maxDepthWithValue(root->left, value); int rr = maxDepthWithValue(root->right, value); return 1 + max(ll, rr); } };
No comments:
Post a Comment