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 };
  • 相关阅读:
    正则表达式入门
    Tyvj 1518 CPU监控——极恶线段树
    数据结构-元组
    洛谷P3195 玩具装箱TOY
    数据结构-列表基本语法
    P2569 股票交易
    列表循环
    P3507 GRA-The Minima Game
    数据结构-集合
    洛谷P1595 信封问题
  • 原文地址:https://www.cnblogs.com/mengchunchen/p/8583075.html
Copyright © 2011-2022 走看看