zoukankan      html  css  js  c++  java
  • [LeetCode] 687. 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.

    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.

    最长同值路径。

    题意是给一个二叉树,请输出一个最长的同值路径的长度。

    思路是后序遍历,可参考250题,也是在找一条可能不会经过根节点的最长路径。同样也是需要创建一个全局变量记录这个路径长度。后序遍历递归的时候判断左右孩子的 val 跟当前节点的 val 是否相等。res记录的是Math.max(res, left + right)。

    时间O(n)

    空间O(n)

    Java实现

     1 class Solution {
     2     int res = 0;
     3 
     4     public int longestUnivaluePath(TreeNode root) {
     5         if (root == null)
     6             return 0;
     7         helper(root);
     8         return res;
     9     }
    10 
    11     private int helper(TreeNode root) {
    12         if (root == null)
    13             return 0;
    14         int left = helper(root.left);
    15         int right = helper(root.right);
    16         if (root.left != null) {
    17             left += root.left.val == root.val ? 1 : -left;
    18         }
    19         if (root.right != null) {
    20             right += root.right.val == root.val ? 1 : -right;
    21         }
    22         res = Math.max(res, left + right);
    23         return Math.max(left, right);
    24     }
    25 }

    JavaScript实现

     1 /**
     2  * @param {TreeNode} root
     3  * @return {number}
     4  */
     5 var longestUnivaluePath = function (root) {
     6     var max = 0;
     7     var helper = function (root) {
     8         if (root == null) {
     9             return 0;
    10         }
    11         var left = helper(root.left);
    12         var right = helper(root.right);
    13         if (root.left) {
    14             left += root.left.val === root.val ? 1 : -left;
    15         }
    16         if (root.right) {
    17             right += root.right.val === root.val ? 1 : -right;
    18         }
    19         max = Math.max(max, left + right);
    20         return Math.max(left, right);
    21     };
    22     helper(root);
    23     return max;
    24 };

    相关题目

    250. Count Univalue Subtrees

    687. Longest Univalue Path

    LeetCode 题目总结

  • 相关阅读:
    沟通,你都做了什么
    Markdown,你只需要掌握这几个
    一周心态-情景联想
    一周心态-漫谈计划之死
    我的Git之旅(1)---git安装、github注册以及一些基本命令
    我的20132014
    Python 笔记——4 条件控制
    Python 笔记——3 数据类型
    Python 笔记——1语法分析
    纯CSS实现兼容ie6以上的圆角头像
  • 原文地址:https://www.cnblogs.com/cnoodle/p/12515166.html
Copyright © 2011-2022 走看看