前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >LWC 52:687. Longest Univalue Path

LWC 52:687. Longest Univalue Path

作者头像
用户1147447
发布2018-01-02 10:51:06
5860
发布2018-01-02 10:51:06
举报
文章被收录于专栏:机器学习入门

LWC 52:687. Longest Univalue Path

传送门:687. Longest Univalue Path

Problem:

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:

代码语言:javascript
复制
          5
         / \
        4   5
       / \   \
      1   1   5

Output: 2

Example 2:

Input:

代码语言:javascript
复制
          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.

思路: 此题的trick在于如何划分子问题,首先对于原问题的划分如下:

如果最长path经过根节点,则计算出来

否则,分别从左子树和右子树中找出最长路径(不经过根节点)

接下来,只需要计算从某个根结点出发,分别链接左子树的最大路径长度和右子树的最大路径长度。

此处的原问题划分如下:

计算左子树的最大长度

计算右子树的最大长度

如果左右子树根节点的val和它们的父结点val相同,则取其中长度最大的。

代码如下:

代码语言:javascript
复制
    public int longestUnivaluePath(TreeNode root) {
        if (root == null) return 0;
        int val = root.val;
        int res = 0;
        if (root.left != null && root.left.val == val) {
            res = 1 + dfs(root.left);
        }
        if (root.right != null && root.right.val == val) {
            res += 1 + dfs(root.right);
        }
        return Math.max(res, Math.max(longestUnivaluePath(root.left), longestUnivaluePath(root.right)));
    }

    public int dfs(TreeNode root) {
        if (root == null) return 0;
        int res = 0;
        int val = root.val;

        if (root.left != null && root.left.val == val) {
            res = 1 + dfs(root.left);
        }

        if (root.right != null && root.right.val == val) {
            res = Math.max(res, 1 + dfs(root.right));
        }
        return res;
    }  
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2017-10-02 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • LWC 52:687. Longest Univalue Path
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档