687. Longest Univalue Path

Description

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:

tree

Output:

2

Example 2:

Input:

tree

Output:

2

Note: The given binary tree has not more than 10000 nodes. The height of the tree is not more than 1000.

Solution

DFS

这道题的思路跟"543. Diameter of Binary Tree"完全相同。

/**
 * 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;
        }
        
        int leftPath = longestUnivaluePath(root.left);
        int rightPath = longestUnivaluePath(root.right);
        int rootPath = univalueDepth(root.left, root) 
            + univalueDepth(root.right, root);
    
        return Math.max(rootPath, Math.max(leftPath, rightPath));
    }
    
    public int univalueDepth(TreeNode node, TreeNode target) {
        if (node == null || node.val != target.val) {
            return 0;
        }
        
        return 1 + Math.max(univalueDepth(node.left, target)
                            , univalueDepth(node.right, target));
    }
}

或者这样写,更清晰,而且是O(n):

/**
 * 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) {
        return dfs(root)[1];
    }
    
    private int[] dfs(TreeNode root) {
        if (root == null) {
            return new int[] {0, 0};
        }
        
        int noCrossRoot = 0;
        int crossRoot = 0;
        int subMax = 0;

        if (root.left != null) {
            int[] left = dfs(root.left);
            if (root.val == root.left.val) {
                noCrossRoot = 1 + left[0];
                crossRoot = noCrossRoot;
            }
            subMax = Math.max(left[1], subMax);
        }
        
        if (root.right != null) {
            int[] right = dfs(root.right);
            if (root.val == root.right.val) {
                noCrossRoot = Math.max(1 + right[0], noCrossRoot);
                crossRoot += 1 + right[0];
            }
            subMax = Math.max(right[1], subMax);
        }
        
        return new int[] {noCrossRoot, Math.max(crossRoot, subMax)};
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • html,xml,xhtml有什么区别? -html是语法较为松散的,不严格的web语言-xml是扩展标记语言,主...
    取个名字都不行阅读 162评论 0 0
  • 周末去陆总貌似成了惯例。晚上7点和伯伯一起走出医院陪他去公交车站,看着他拎着饭盒奔向613的背影,我想这医院短期内...
    苏小文S阅读 367评论 0 1
  • 为什么选择在大年初二看《狼图腾》?大约是因为大年初一看了《澳门风云2》吧。 虽然是一个电影爱好者,但是已经很久没有...
    言姱阅读 385评论 0 1