File tree 1 file changed +42
-0
lines changed
1 file changed +42
-0
lines changed Original file line number Diff line number Diff line change 7
7
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
8
8
* };
9
9
*/
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)
10
52
class Solution {
11
53
int longestUnivaluePath (TreeNode* root, int val) {
12
54
if (!root or root->val != val) return 0 ;
You can’t perform that action at this time.
0 commit comments