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

    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.

    time: O(n), space: O(height)

    /**
     * Definition for a binary tree node.
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode(int x) { val = x; }
     * }
     */
    class Solution {
        int length = 0;
        
        public int longestUnivaluePath(TreeNode root) {
            if(root == null) {
                return 0;
            }
            helper(root);
            return length;
        }
        
        public int helper(TreeNode root) {
            if(root == null) {
                return 0;
            }
            int l = helper(root.left);
            int r = helper(root.right);
            int left = 0, right = 0;
            if(root.left != null && root.val == root.left.val) {
                left = l + 1;
            }
            if(root.right != null && root.val == root.right.val) {
                right = r + 1;
            }
            length = Math.max(length, left + right);
            return Math.max(left, right);
        }
    }
  • 相关阅读:
    启动时间知多少?8款音视频类应用测评报告分析
    优化信息流很麻烦?三招教你轻松搞定
    vmstat
    iostat
    dstat
    strace
    Mysql(一)
    rsync
    Kubernetes-深入分析集群安全机制
    Kubernetes-apiserver
  • 原文地址:https://www.cnblogs.com/fatttcat/p/10198584.html
Copyright © 2011-2022 走看看