zoukankan      html  css  js  c++  java
  • Leetcode 687.最长同值路径

    最长同值路径

    给定一个二叉树,找到最长的路径,这个路径中的每个节点具有相同值。 这条路径可以经过也可以不经过根节点。

    注意:两个节点之间的路径长度由它们之间的边数表示。

    示例 1:

    输入:

    输出:

    2

    示例 2:

    输入:

    输出:

    2
    

    注意: 给定的二叉树不超过10000个结点。 树的高度不超过1000。

    思路

    Intuition

    We can think of any path (of nodes with the same values) as up to two arrows extending from it's root.

    Specifically, the root of a path will be the unique node such that the parent of that node does not appear in the path, and an arrow will be a path where the root only has one child node in the path.

    Then, for each node, we want to know what is the longest possible arrow extending left, and the longest possible arrow extending right? We can solve this using recursion.

    Algorithm

    Let arrow_length(node) be the length of the longest arrow that extends from the node. That will be 1 + arrow_length(node.left) if node.left exists and has the same value as node. Similarly for the node.right case.

    While we are computing arrow lengths, each candidate answer will be the sum of the arrows in both directions from that node. We record these candidate answers and return the best one.

     1 class Solution {
     2     int ans;
     3     public int longestUnivaluePath(TreeNode root) {
     4         ans = 0;
     5         arrowLength(root);
     6         return ans;
     7     }
     8     public int arrowLength(TreeNode node) {
     9         if (node == null) return 0;
    10         int left = arrowLength(node.left)
    11         int right = arrowLength(node.right);
    12         int arrowLeft = 0, arrowRight = 0;
    13         if (node.left != null && node.left.val == node.val) {
    14             arrowLeft += left + 1;
    15         }
    16         if (node.right != null && node.right.val == node.val) {
    17             arrowRight += right + 1;
    18         }
    19         ans = Math.max(ans, arrowLeft + arrowRight);
    20         return Math.max(arrowLeft, arrowRight);
    21     }
    22 }

  • 相关阅读:
    实验四: Android程序设计
    实验三 敏捷开发与XP实践-1
    mini dc课堂练习补交
    20155216 2016-2017-2 《Java程序设计》第十周学习总结
    第十二周课上练习
    20155210 潘滢昊 Java第三次实验
    20155210 2016-2017-2 《Java程序设计》第10周学习总结
    20155210 潘滢昊2016-2017-2 《Java程序设计》第9周学习总结
    20155210潘滢昊 Java第二次试验
    20155210潘滢昊 2016-2017-2 《Java程序设计》第8周学习总结
  • 原文地址:https://www.cnblogs.com/kexinxin/p/10400351.html
Copyright © 2011-2022 走看看