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
  • 相关阅读:
    poj 1733 Parity game
    poj 1456 Supermarket
    bzoj 1304 [CQOI 2009] 叶子的染色
    51Nod 1667 概率好题
    2015年阿里巴巴校招研发工程师在线笔试题汇总
    从字符串常量起说内存分配
    字符串笔面试题
    排序算法(4)-线性时间排序
    华为2015校园招聘机试
    笔画宽度变化(C++和matlab算法)
  • 原文地址:https://www.cnblogs.com/immjc/p/7778291.html
Copyright © 2011-2022 走看看