687. 最长同值路径(和543相似,返回值不同,因为意义不同)

给定一个二叉树,找到最长的路径,这个路径中的每个节点具有相同值。 这条路径可以经过也可以不经过根节点。

注意:两个节点之间的路径长度由它们之间的边数表示。

示例 1:

输入:

              5
             / \
            4   5
           / \   \
          1   1   5
输出:

2
示例 2:

输入:

              1
             / \
            4   5
           / \   \
          4   4   5
输出:

2
注意: 给定的二叉树不超过10000个结点。 树的高度不超过1000。
class Solution {
    int max = 0;
    public int dfs(TreeNode root){
        if(root == null)
            return 0;
        int leftN = dfs(root.left);
        int rightN = dfs(root.right);

        leftN = (root.left != null && root.left.val == root.val) ? leftN+1 : 0;        
        rightN = (root.right != null && root.right.val == root.val) ? rightN+1 : 0;

        max = Math.max(max,leftN + rightN);
        return Math.max(leftN,rightN);
    }
    public int longestUnivaluePath(TreeNode root) {
        dfs(root);
        return max;
    }
}

逻辑清晰点:

class Solution {
    int max = 0;
    public int dfs(TreeNode root){
        if(root == null)
            return 0;
        int left = dfs(root.left);
        int right = dfs(root.right);       

        if(root.left != null && root.left.val == root.val)
            left++;
        else
            left = 0;        
        if(root.right != null && root.right.val == root.val)
            right++;
        else
            right = 0;        
        max = Math.max(max,left + right);        
        return Math.max(left,right);        
    }
    public int longestUnivaluePath(TreeNode root) {
         dfs(root);      
        return max;
    }
}

首先对其左右孩子调用递归函数,得到其左右孩子的最大同值路径,然后根据其与左右孩子的关系来判断结果。
如果root的值与其左孩子的值相同,那么从左孩子得到的路径值需要加一;如果不相同,那么置零。右孩子同理。
然后最大值max就是当前的最大值或者左右孩子路径的和。
返回值是左右路径中的最大值,因为它还需要和父节点继续构建路径。

注意:必须先进行递归,在进行关系判断!

猜你喜欢

转载自blog.csdn.net/xuchonghao/article/details/80692887
今日推荐