Leetcode算法学习日志-687 Longest Univalue Path

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.

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

题意分析

找起点和中点间的点值都是相同的最长路的长度,长度定义为边数。注意没有限制从上到下。

解法分析

本题还是采用深度优先搜索,用递归的方法解,子问题就是从一个root开始向下的最长相同点值路的最大值,注意要包含root,将该点的两个子树最长路(包含root)的长度加起来可以得到一条路,在所有这样的路中取最大值即为所求。C++代码如下:

class Solution {
private:
    int longest=0;
public:
    int longestPathContainRoot(TreeNode* root){//the longest path that contains root,from top to bottom
        int nextLen;
        int lenL=0,lenR=0;
        int temp=0;
        if((root->left==NULL)&&(root->right==NULL))
            return 0;
        if(root->left!=NULL){
            nextLen=longestPathContainRoot(root->left);
            if(root->val==(root->left)->val){
                lenL=nextLen+1;
                temp+=lenL;  
            }  
            else
                lenL=0;   
        }  
        if(root->right!=NULL){
            nextLen=longestPathContainRoot(root->right);
            if(root->val==(root->right)->val){
                lenR=nextLen+1;
                temp+=lenR;
            }   
            else
                lenR=0;
        }
        longest=max(longest,temp);
        return max(lenL,lenR);
        
    }
    int longestUnivaluePath(TreeNode* root) {
        if(root==NULL)
            return 0;
        int k=longestPathContainRoot(root);
        return longest;  
    }
};
代码中递归过程单独用了一个函数,递归函数每次返回每个包含该root的自上而下的最长路的长度,最终程序返回满足题意的最长路的长度。


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值