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)};
    }
}

你可能感兴趣的:(687. Longest Univalue Path)