1085. Longest Univalue Path

class Solution { public: /** * @param root: * @return: the length of the longest path where each node in the path has the same value */ int longestUnivaluePath(TreeNode * root) { // Write your code here if(root == NULL){ return 0; } int res = 0; find(root, res); return res; } int find(TreeNode *root, int &res){ if(root == NULL){ return 0; } // if(root->left == NULL && root->right == NULL){ // return 1; // } int left = find(root->left, res); int right = find(root->right, res); //这里一定要先执行了 int left1 = 0, right1 = 0; if(root->left != NULL){ if(root->left->val == root->val){ left1 = 1 + left; } } if(root->right){ if(root->right->val == root->val){ right1 = 1 + right; } } res = max(res, left1 + right1); return max(left1, right1); } };

Comments

Popular posts from this blog

算法的比较