LeetCode-687. Longest Univalue Path

Description

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

1.The length of path between two nodes is represented by the number of edges between them.
2.The given binary tree has not more than 10000 nodes. The height of the tree is not more than 1000.

Example 1

Input:

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

2

Example 2

Input:

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

2

Solution 1(C++)

class Solution {
public:
    int longestUnivaluePath(TreeNode* root) {
        if (!root) return 0;
        int longestPath=0;
        helper(root, longestPath);
        return longestPath;
    }
private:
    int helper(TreeNode* root, int& m){
        int l=root->left ? helper(root->left, m) : 0;
        int r=root->right ? helper(root->right, m) : 0;
        l=(root->left && root->left->val==root->val) ? l+1 : 0;
        r=(root->right && root->right->val==root->val) ? r+1 : 0;
        m=max(m,l+r);
        return max(l,r);
    }
};

算法分析

这道题我认为可以看成是最长连续序列与树的结合。利用动态规划的方法可以解决。观察每一个节点。每一个节点所在可能路径最长相同连续序列的长度其实与其左子节点与右子节点有关,考虑到连续序列的特性,一旦不连续了,即根节点的值与左子节点或者与右子节点的值不相等了,那么左边的或者右边的就为0,如果相等,那么左边的或者右边的就各自加1。

这里要注意,关于长度的定义,两个节点长度为1,那么可以认为长度初始值为0,那么每新加一个节点,长度加1。

还是有些地方说不太清楚,给这个题目打了个心,以后在做一做。

程序分析

略。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值