[LeetCode] 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:

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.

这道题让我们求最长的相同值路径,跟之前那道Count Univalue Subtrees十分的类似,解法也很类似。对于这种树的路径问题,递归是不二之选。在递归函数中,我们首先对其左右子结点调用递归函数,得到其左右子树的最大相同值路径,下面就要来看当前结点和其左右子结点之间的关系了,如果其左子结点存在且和当前节点值相同,则left自增1,否则left重置0;同理,如果其右子结点存在且和当前节点值相同,则right自增1,否则right重置0。然后用left+right来更新结果res。而调用当前节点值的函数只能返回left和right中的较大值,因为如果还要跟父节点组path,就只能在左右子节点中选一条path,当然选值大的那个了,参见代码如下:

解法一:

class Solution {

public:
    int longestUnivaluePath(TreeNode* root) {
        if (!root) return 0;
        int res = 0;
        helper(root, root, res);
        return res;
    }
    int helper(TreeNode* node, TreeNode* parent, int& res) {
        if (!node) return 0;
        int left = helper(node->left, node, res);
        int right = helper(node->right, node, res);
        left = (node->left && node->val == node->left->val) ? left + 1 : 0;
        right = (node->right && node->val == node->right->val) ? right + 1 : 0;
        res = max(res, left + right);
        return max(left, right);
    }
};

下面这种解法使用了两个递归函数,使得写法更加简洁了,首先还是先判断root是否为空,是的话返回0。然后对左右子节点分别调用当前函数,取其中较大值保存到变量sub中,表示左右子树中最长的相同值路径,然后就是要跟当前树的最长相同值路径比较,计算方法是对左右子结点调用一个helper函数,并把当前结点值传进去,把返回值加起来和sub比较,去较大值返回。在helper函数里,当当前结点为空,或者当前节点值不等于父结点值的话,返回0。否则结返回对左右子结点分别调用helper递归函数中的较大值加1,我们发现这种写法跟求树的最大深度很像,参见代码如下:

解法二:

class Solution {

public:
    int longestUnivaluePath(TreeNode* root) {
        if (!root) return 0;
        int sub = max(longestUnivaluePath(root->left), longestUnivaluePath(root->right));
        return max(sub, helper(root->left, root->val) + helper(root->right, root->val));
    }
    int helper(TreeNode* node, int parent) {
        if (!node || node->val != parent) return 0;
        return 1 + max(helper(node->left, node->val), helper(node->right, node->val));
    }
};

本文转自博客园Grandyang的博客,原文链接:[LeetCode] Longest Univalue Path 最长相同值路径

,如需转载请自行联系原博主。

时间: 2024-10-27 00:15:34

[LeetCode] Longest Univalue Path 最长相同值路径的相关文章

[LeetCode] Path Sum IV 二叉树的路径和之四

If the depth of a tree is smaller than 5, then this tree can be represented by a list of three-digits integers. For each integer in this list: The hundreds digit represents the depth D of this node, 1 <= D <= 4. The tens digit represents the positio

[LeetCode] Longest Word in Dictionary 字典中的最长单词

Given a list of strings words representing an English Dictionary, find the longest word in words that can be built one character at a time by other words in words. If there is more than one possible answer, return the longest word with the smallest l

[LeetCode] Longest Continuous Increasing Subsequence 最长连续递增序列

Given an unsorted array of integers, find the length of longest continuous increasing subsequence. Example 1: Input: [1,3,5,4,7] Output: 3 Explanation: The longest continuous increasing subsequence is [1,3,5], its length is 3. Even though [1,3,5,7] i

跳转-jsp里面的path,转发后地址栏路径变化了,前后两次路径,怎么填写注册按钮路径??

问题描述 jsp里面的path,转发后地址栏路径变化了,前后两次路径,怎么填写注册按钮路径?? 登录页面要有两个按钮,一个登录,一个提交.如果用户点击登录按钮会跳转到servlet里面,这个时候是转发实现的,假如说登录不成功,又转发回login.jsp页面了.这个时候因为是转发,所以地址是--/servlet页面,这个时候想在点击注册按钮的时候,这个路径跟刚开始--/login.jsp不一样了,所以面对这种情况,这个注册按钮的路径怎么解决?????????? 解决方案 前面加个{path}也不行

[LeetCode] Longest Increasing Subsequence

Given an unsorted array of integers, find the length of longest increasing subsequence. For example, Given [10, 9, 2, 5, 3, 7, 101, 18], The longest increasing subsequence is [2, 3, 7, 101], therefore the length is 4. Note that there may be more than

[LeetCode]64.Minimum Path Sum

[题目] Given a m x n grid filled with non-negative numbers, find a path from top left to bottom right which minimizes the sum of all numbers along its path. Note: You can only move either down or right at any point in time. [思路] 设sum[i][j] 到位置(i,j)时路径最

[LeetCode] Longest Substring Without Repeating Characters

Given a string, find the length of the longest substring without repeating characters. For example, the longest substring without repeating letters for "abcabcbb" is "abc", which the length is 3. For "bbbbb" the longest subst

[LeetCode]--71. Simplify Path

Given an absolute path for a file (Unix-style), simplify it. For example, path = "/home/", => "/home" path = "/a/./b/../../c/", => "/c" click to show corner cases. Corner Cases: Did you consider the case where

[LeetCode] Longest Palindromic Substring

Given a string S, find the longest palindromic substring in S. You may assume that the maximum length of S is 1000, and there exists one unique longest palindromic substring. 解题思路 网上有一种思路是说先得到输入字符串的反转字符串,然后用动态规划得到这两个字符串的最长子串即可,但是实际上这种方式有问题.例如,对于输入"ab