LeetCode-c++最长同值路径(题687)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/glw0223/article/details/88628990

题面

给定一个二叉树,找到最长的路径,这个路径中的每个节点具有相同值。 这条路径可以经过也可以不经过根节点。
注意:两个节点之间的路径长度由它们之间的边数表示。
示例 1:
输入:

          5
         / \
        4   5
       / \   \
      1   1   5

输出:2
示例 2:
输入:

          1
         / \
        4   5
       / \   \
      4   4   5

输出:2
注意: 给定的二叉树不超过10000个结点。 树的高度不超过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 longestUnivaluePath(TreeNode* root) {
        res = 0;
        longestUnivalue(root);
        return res;
    }
private:
    int res;
    int longestUnivalue(TreeNode* root)
    {
        if (root == nullptr){
            return 0;
        }
        int l = longestUnivalue(root->left);
        int r = longestUnivalue(root->right);
        int pl = 0, pr = 0;
        if (root->left && root->left->val == root->val){
           pl = l + 1; 
        } 
        if (root->right && root->right->val == root->val){
            pr = r + 1;
        } 
        res = max(res, pl + pr);
        return max(pl, pr);
    }
};

复杂度

  • 时间复杂度: O ( N ) O(N) ,其中 N N 是树中节点数。因为处理每个节点一次。
  • 空间复杂度: O ( H ) O(H) ,其中 H H 是树的高度。因为递归调用栈可以达到 H H 层的深度。

猜你喜欢

转载自blog.csdn.net/glw0223/article/details/88628990