算法——Week9

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.

Note: 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.


解题思路
题目要求是找出值最大路径,并且要求路径上的每个节点的值必须相同。我使用递归算法,基于深度优先,从根节点开始遍历整个树,找出所有满足条件的路径并比较出最大的一个作为结果输出。


代码如下:

/**
 * 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 {
public:
    int ans = 0;
    int longestUnivaluePath(TreeNode* root) {
        dfs(root);
        return ans;
    }
    int dfs(TreeNode *root) {
        if(root == NULL ) {
            return 0;
        }
        int left = dfs(root->left);
        int right = dfs(root->right);
        int ans_left = 0;
        int ans_right = 0;
        if(root->left != NULL && root->left->val == root->val) {
            ans_left += left + 1;
        }
        if(root->right != NULL && root->right->val == root->val) {
            ans_right += right + 1;
        }
        ans = ans > ans_left + ans_right ? ans : ans_left + ans_right;
        return ans_left > ans_right ? ans_left : ans_right;
    }
};

猜你喜欢

转载自blog.csdn.net/melwx/article/details/85273999