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.

    找出相同节点相连的路径,求最长的边数和

    C++(71ms):

     1 /**
     2  * Definition for a binary tree node.
     3  * struct TreeNode {
     4  *     int val;
     5  *     TreeNode *left;
     6  *     TreeNode *right;
     7  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
     8  * };
     9  */
    10 class Solution {
    11 public:
    12     int longestUnivaluePath(TreeNode* root) {
    13         int res = 0 ;
    14         if (root)
    15             dfs(root , res) ;
    16         return res ;
    17         
    18     }
    19     
    20     int dfs(TreeNode* root , int& res){
    21         int l = root->left ? dfs(root->left , res) : 0 ;
    22         int r = root->right ? dfs(root->right , res) : 0 ;
    23         
    24         int leftEdge = (root->left && root->left->val == root->val) ? l + 1 : 0 ;
    25         int rightEdge = (root->right && root->right->val == root->val) ? r + 1 : 0 ;
    26         res = max(res , leftEdge + rightEdge) ;
    27         return max(leftEdge , rightEdge) ;
    28     }
    29 };
  • 相关阅读:
    软件乘法实现
    矩阵连乘求解优化
    { 控件动态创建的堆与栈 }
    digital clock based C
    C++初探
    C语言语法教程-链表
    EF Core 实现读写分离的最佳方案
    Windows Terminal 安装及美化
    .netcore centos环境搭建实战
    AutoMapper.RegExtension 介绍
  • 原文地址:https://www.cnblogs.com/mengchunchen/p/8583075.html
Copyright © 2011-2022 走看看