Longest Univalue Path

157 阅读1分钟

原文:https://leetcode.com/problems/longest-univalue-path/description/

给定一个二叉树,找到最长的路径,这条路径上的值都相同



第一感觉就是树的深搜,从root开始依次判断每一个父节点到底有几个相同的子节点。

class Solution {
    int res = 0;
    public int longestUnivaluePath(TreeNode root) {
        if(root ==null)
            return res; 
             dfs(root);

            return res;
    }
   
    
    public void  dfs(TreeNode root){
        if(root==null)return;
        int temp = count(root.left,root.val)+count(root.right,root.val);
        res = Math.max(res,temp);
      dfs(root.left);
        dfs(root.right);
            
    }
    public int count(TreeNode root,int val){
        if(root == null || root.val!=val ) return 0;
          int left = count(root.left,val) + 1;
          int right = count(root.right,val) + 1;
        
        return Math.max(left,right);                 
    }
    
}

这样,每个节点有记录了与他相同节点的个数。