LeetCode687.最长同值路径

在这里插入图片描述
思路:
我自己写的,时间复杂度是O(n^2)

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public int longestUnivaluePath(TreeNode root) {
        if(root == null){
            return 0;
        }
        path = Math.max(path,valuepath(root.left,root.val) + valuepath(root.right,root.val));
        longestUnivaluePath(root.left);
        longestUnivaluePath(root.right);
        return path;
    }
    int path = 0;
    public int valuepath(TreeNode root,int val){
        if(root == null || root.val != val){
            return 0;
        }
        int l = 0;
        int r = 0;
        if(root.left != null && root.val == val && root.val == root.left.val){
            l = valuepath(root.left,val);
        }
        if(root.right != null && root.val == val && root.val == root.right.val){
            r = valuepath(root.right,val);
        }
        return Math.max(l,r)+1;
    }
   
}

2.根据LeetCode题解来做,太强了,时间复杂度是O(N)

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    int path = 0;
    public int longestUnivaluePath(TreeNode root) {
        if(root == null){
            return 0;
        }
        helper(root);
        return path;
    }
    public int helper(TreeNode root){
        if(root == null){
            return 0;
        }
        int left = helper(root.left);
        int right = helper(root.right);
        int kl = 0,kr = 0;
        if(root.left != null && root.val == root.left.val){
            kl = left + 1;
        }
        if(root.right != null && root.val == root.right.val){
            kr = right + 1;
        }
        path = Math.max(path,kr+kl);
        return Math.max(kl,kr);
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值