← Home

687. Longest Univalue Path

LeetCode article · C++ solution
Website made by wuisabel-gif · Original C++ code by keineahnung2345
two pointersC++Markdown
687

Let's make this one less mysterious. For 687. Longest Univalue Path, the solution in this repository is mainly a two pointers solution.

Guide

What?

We want to turn the problem statement into a smaller set of decisions the computer can repeat safely. Instead of trying to be clever immediately, read the code as a sequence of questions:

  • What state are we keeping?
  • How do we move from one state to the next?
  • When do we know the answer is already determined?

For this file, the main tools are: two pointers.

Guide

When?

This pattern shows up when the brute force version has too many repeated checks, too many possible branches, or too much bookkeeping to do by hand. The accepted code reduces that pressure by storing exactly the information that remains useful later.

The important function names to track are longestUnivaluePath, arrowLength.

Guide

Why?

The point of the implementation is not to make the code longer. It is to avoid doing the same thinking twice.

  • The final return is not magic; it is the invariant after the loops or recursion have finished doing their accounting.

Guide

How?

Walk through the solution in this order:

  1. Initialize the memory or helper structure.
  2. Process candidates in the order the invariant expects.
  3. Update the answer only when the current state is valid.
  4. Return the value that represents the fully processed input.

The most important competitive-programming habit here is to trust the invariant. Once the invariant is right, the loops become much less scary.

Guide

Complexity

  • Time: O(n) to O(n log n), depending on the dominant loop or data structure operation
  • Space: O(n) in the usual case for auxiliary containers or recursion

Guide

C++ Solution

Your submission

The accepted solution

solution.cpp
01//Runtime: 196 ms, faster than 9.46% of C++ online submissions for Longest Univalue Path.
02//Memory Usage: 50.5 MB, less than 16.07% of C++ online submissions for Longest Univalue Path.
03
04/**
05 * Definition for a binary tree node.
06 * struct TreeNode {
07 *     int val;
08 *     TreeNode *left;
09 *     TreeNode *right;
10 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
11 * };
12 */
13class Solution {
14public:
15    struct paths {
16        int a; //length of path can be elongated
17        int b; //length of path can't be elongated
18        paths() {};
19        paths(int init_a, int init_b) {
20            a = init_a;
21            b = init_b;
22        }
23    };
24    
25    paths rLongestUnivaluePath(TreeNode* root){
26        if(root==NULL) return paths(0, 0);
27        //leaf node
28        if(root->left==NULL && root->right==NULL) return paths(0, 0);
29        
30        paths pl = rLongestUnivaluePath(root->left);
31        paths pr = rLongestUnivaluePath(root->right);
32        
33        //only one side
34        if(root->left!=NULL && root->right==NULL){
35            if(root->val == root->left->val){
36                return paths(pl.a+1, pl.b);
37            }else{
38                return paths(0, max(pl.a, pl.b));
39            }
40        }
41        if(root->right!=NULL && root->left==NULL){
42            if(root->val == root->right->val){
43                return paths(pr.a+1, pr.b);
44            }else{
45                return paths(0, max(pr.a, pr.b));
46            }
47        }
48        if(root->val == root->left->val && root->val == root->right->val){
49            return paths(max(pl.a, pr.a)+1, max(pl.a+pr.a+2, max(pl.b, pr.b)));
50        }else if(root->val == root->left->val){
51            //need to consider the other side when calculating b!
52            return paths(pl.a+1, max(max(pr.a, pr.b), pl.b));
53        }else if(root->val == root->right->val){
54            return paths(pr.a+1, max(max(pl.a, pl.b), pr.b));
55        }
56        // cout << pl.a << " " << pl.b << " " << pr.a << " "  << pr.b << endl; 
57        return paths(0, max(max(pl.a, pl.b), max(pr.a, pr.b)));
58    }
59    
60    int longestUnivaluePath(TreeNode* root) {
61        paths p = rLongestUnivaluePath(root);
62        return max(p.a, p.b);
63    }
64};
65
66//solution: recursion
67//Runtime: 140 ms, faster than 86.08% of C++ online submissions for Longest Univalue Path.
68//Memory Usage: 49.5 MB, less than 100.00% of C++ online submissions for Longest Univalue Path.
69//Time Complexity: O(N), where N is the number of nodes in the tree. We process every node once.
70//Space Complexity: O(H), where H is the height of the tree. Our recursive call stack could be up to H layers deep.
71
72/**
73 * Definition for a binary tree node.
74 * struct TreeNode {
75 *     int val;
76 *     TreeNode *left;
77 *     TreeNode *right;
78 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
79 * };
80 */
81class Solution {
82public:
83    int ans;
84    int arrowLength(TreeNode* node){
85        if(!node) return 0;
86        int l = arrowLength(node->left);
87        int r = arrowLength(node->right);
88        int arrL = 0, arrR = 0;
89        //if the two conditions do not hold,
90        //it means the path breaks here,
91        //so arrL and arrR will be 0
92        if(node->left && node->left->val == node->val){
93            //arrL will remain 0 if the condition do not hold
94            arrL = l+1;
95        }
96        if(node->right && node->right->val == node->val){
97            arrR = r+1;
98        }
99        //arrL + arrR is the length of univaluepath of current node
100        //ans stores the max of them
101        ans = max(ans, arrL + arrR);
102        //the length of uni direction path
103        return max(arrL, arrR);
104    }
105    
106    int longestUnivaluePath(TreeNode* root) {
107        ans = 0;
108        arrowLength(root);
109        return ans;
110    }
111};

Cost

Complexity

Time
O(n) to O(n log n), depending on the dominant loop or data structure operation
Dominated by the main traversal, recursion, or data-structure operations in the code.
Space
O(n) in the usual case for auxiliary containers or recursion
Auxiliary state plus the answer structure where the problem requires one.