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);
    }
}
发布了169 篇原创文章 · 获赞 5 · 访问量 7712

猜你喜欢

转载自blog.csdn.net/fsdgfsf/article/details/104327754