zoukankan      html  css  js  c++  java
  • [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:

    2

    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.

    寻找由相同值组成的最长路径(路径可以不经过根节点),对于关于树的路径问题应该是递归的思想来解题。

    首先应该找出该问题的子问题,也就是说树的最小部分问题。也就是如果一个父节点与其子节点值相同,则将其计数+1。一般情况下,一个父节点存在两个子节点,这时需要判断它的左子树的计数大还是右子树计算大。返回较大的那个值,同时还需要更新每个节点的最大路径。

    /**
     * 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) {
            int lup = 0;
            if (root != nullptr)
                dfs(root, lup);
            return lup;
        }
        int dfs(TreeNode* node, int& lup) {
            int l = node->left ? dfs(node->left, lup) : 0;
            int r = node->right ? dfs(node->right, lup) : 0;
            int resl = node->left && node->left->val == node->val ? l + 1 : 0;
            int resr = node->right && node->right->val == node->val ? r + 1 : 0;
            lup = max(lup, resl + resr);
            return max(resl, resr);
        }
    };
    // 99 ms
  • 相关阅读:
    解决web网页访问慢的问题
    Django安装配置(for Mac)
    Django安装(for Mac)
    HTML5中的新事件
    关于http-equiv
    【转】@fant-face
    textarear中的value....还是...innertext
    清除浮动的元素的margin-top触碰不到,浮动元素的边界
    常用排序算法总结(一)
    JS常用特效方法总结
  • 原文地址:https://www.cnblogs.com/immjc/p/7778291.html
Copyright © 2011-2022 走看看