【LeetCode 687】Longest Univalue Path

題目描述

Given a binary tree, find the length of the longest path where each node in the path has the same value. This path may or may not pass through the root.

The length of path between two nodes is represented by the number of edges between them.

Example 1:

Input:

              5
             / \
            4   5
           / \   \
          1   1   5
Output: 2

Example 2:

Input:

              1
             / \
            4   5
           / \   \
          4   4   5
Output: 2

Note: The given binary tree has not more than 10000 nodes. The height of the tree is not more than 1000.

思路

dfs,對每個節點找左邊的一樣的點的個數,右邊的一樣的點的個數。過程中維護最大值。

代碼

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    int res = 0;
    int longestUnivaluePath(TreeNode* root) {
        int res = 0;
        path(root, &res);
        return res;
    }
    
    int path(TreeNode* root, int* res) {
        if (root == NULL) return 0;
        int l = path(root->left, res);
        int r = path(root->right, res);
        int pl = 0, pr = 0;
        if (root->left && root->val == root->left->val) pl = l + 1;
        if (root->right && root->val == root->right->val) pr = r + 1;
        *res = max(*res, pl+pr);
        return max(pl, pr);
    }
};
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章