Skip to content

Instantly share code, notes, and snippets.

@s4553711
Created January 27, 2018 15:43
Show Gist options
  • Save s4553711/8fed22daab21c05f92ea49dba7f771ef to your computer and use it in GitHub Desktop.
Save s4553711/8fed22daab21c05f92ea49dba7f771ef to your computer and use it in GitHub Desktop.
/**
* 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:
int longestUnivaluePath(TreeNode* root) {
int res = 0;
if (root) dfs(root, res);
return res;
}
int dfs(TreeNode* node, int &res) {
int l = node->left ? dfs(node->left, res) : 0;
int r = node->right ? dfs(node->right, res) : 0;
int resl = node->left && node->left->val == node->val ? l + 1 : 0;
int resr = node->right && node->right->val == node->val ? r + 1 : 0;
res = max(res, resl + resr);
return max(resl, resr);
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment