Skip to content

Commit c65b5fb

Browse files
committed
O(n) single DFS solution for Longest Univalue Path problem (similar to Diameter of a tree)
1 parent cafdda4 commit c65b5fb

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed

Diff for: source-code/Longest_Univalue_Path.cpp

+42
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,48 @@
77
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
88
* };
99
*/
10+
// with single DFS(like diameter of a tree)
11+
/**
12+
* Definition for a binary tree node.
13+
* struct TreeNode {
14+
* int val;
15+
* TreeNode *left;
16+
* TreeNode *right;
17+
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
18+
* };
19+
*/
20+
class Solution {
21+
int longestUnivaluePath(TreeNode* root, int& longestPath) {
22+
if(!root) return 0;
23+
int leftDepth = longestUnivaluePath(root->left, longestPath);
24+
int rightDepth = longestUnivaluePath(root->right, longestPath);
25+
26+
if(root->left and root->left->val == root->val) {
27+
leftDepth++;
28+
} else {
29+
leftDepth = 0;
30+
}
31+
32+
if(root->right and root->right->val == root->val) {
33+
rightDepth++;
34+
} else {
35+
rightDepth = 0;
36+
}
37+
38+
longestPath = max(longestPath, leftDepth + rightDepth);
39+
40+
return max(leftDepth, rightDepth);
41+
}
42+
public:
43+
int longestUnivaluePath(TreeNode* root) {
44+
int longestPath = 0;
45+
longestUnivaluePath(root, longestPath);
46+
47+
return longestPath;
48+
}
49+
};
50+
51+
// O(n^2)
1052
class Solution {
1153
int longestUnivaluePath(TreeNode* root, int val) {
1254
if(!root or root->val != val) return 0;

0 commit comments

Comments
 (0)