leetcode 687. 最长同值路径

687. 最长同值路径

给定一个二叉树,找到最长的路径,这个路径中的每个节点具有相同值。 这条路径可以经过也可以不经过根节点。

注意:两个节点之间的路径长度由它们之间的边数表示。

示例 1:

输入:

              5
             / \
            4   5
           / \   \
          1   1   5

输出:

2

示例 2:

输入:

              1
             / \
            4   5
           / \   \
          4   4   5

输出:

2

注意: 给定的二叉树不超过10000个结点。 树的高度不超过1000。

扫描二维码关注公众号,回复: 10298570 查看本文章

解题思路: 我一开始想的是用先序 把 相同的的值一直穿下去,以下图举例,floor1(5) 的点设置为1 ,那么 floor2(4)设置为1

floor2(5) 设置为2  ,floor3(1)=1,floor3(5) = 3 ,  但是 可以A掉 一半的点

/**
 * 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 res = 0;
    void DFS(TreeNode* root,int cnt){
        res = res>=cnt ? res : cnt;
        if(!root){
            return ;
        } 
        if(root->left)
            if(root->left->val==root->val)
                DFS(root->left,cnt+1);
            else
                DFS(root->left,1); 
        if(root->right)
            if(root->right->val==root->val)
                DFS(root->right,cnt+1);
            else
                DFS(root->right,1); 
    }
    int longestUnivaluePath(TreeNode* root) {
            // if(!root) return 0;
            DFS(root,1);
            return res - 1;
    }
};

但是还存在这种情况   这个的返回值是 2,所以应该用后后序遍历

/**
 * 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 res = 0;
    
    
    int longestUnivaluePath(TreeNode* root) {
            if(!root) return 0;
            // DFS(root,1);
            calPostOrder(root);
            return res ;
    }
    int calPostOrder(TreeNode* root){
        if(root==NULL) return 0;
        int leftNum = calPostOrder(root->left);
        int rightNum = calPostOrder(root->right);

        int lNum=0,rNum=0;
        if(root->left!=NULL&&root->val==root->left->val)
            lNum = leftNum + 1;
        if(root->right!=NULL&&root->val==root->right->val)
            rNum = rightNum + 1;
        res = max(res,lNum+rNum);
        return max(lNum,rNum);
    }
};
发布了124 篇原创文章 · 获赞 47 · 访问量 7万+

猜你喜欢

转载自blog.csdn.net/ludan_xia/article/details/104954188