題目連結

經典 DFS 題!

AC Code

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
#ifdef LOCAL
#include <bits/stdc++.h>
using namespace std;

// tree node stuff here...
struct TreeNode {
    int val;
    TreeNode *left;
    TreeNode *right;
    TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
#endif

static int __initialSetup = []()
{
    std::ios::sync_with_stdio(false);
    cin.tie(NULL);
    return 0;
}
();

// handle special cases first
// [], "", ...
// range of input?
/**
 * 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
{
private:
    int dfs(TreeNode *root, int &ans)
    {
        if (root == NULL)
            return 0;

        int ret = 0;
        int l = dfs(root->left, ans);
        int r = dfs(root->right, ans);
        if (root->left && root->left->val == root->val)
            ret = max(ret, l + 1);
        if (root->right && root->right->val == root->val)
            ret = max(ret, r + 1);
        if (root->left && root->right && root->right->val == root->val &&
            root->val == root->left->val)
            ans = max(ans, l + 1 + r + 1); // KEY!!

        ans = max(ans, ret);
        return ret;
    }

public:
    int longestUnivaluePath(TreeNode *root)
    {
        int ans = 0;
        dfs(root, ans);
        return ans;
    }
};

#ifdef LOCAL
int main()
{
    return 0;
}
#endif