687-Longest Univalue Path

kevin聰發表於2018-05-03

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:

              5
             / \
            4   5
           / \   \
          1   1   5

Output:

2

Example 2:

Input:

              1
             / \
            4   5
           / \   \
          4   4   5

Output:

2

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


問題描述

給定一個二叉樹, 找出最長路徑(要求路徑上的節點值相同)。路徑可以通過根節點, 也可以不通過

注意:路徑長度由路徑的邊的個數表示


問題分析

後序遍歷, 先獲取左右子樹的最長路徑, 將左右子樹的根節點的值與當前根節點的值比較, 即可得出當前根節點的最長路徑。
(注意將根節點的值傳給左右子樹)


解法

class Solution {
    private int max = 0;

    public int longestUnivaluePath(TreeNode root) {
        if(root == null)    return 0;

        helper(root, root.val);

        return max;
    }
    //注意val這個引數
    private int helper(TreeNode root, int val) {
        if(root == null) return 0;

        int left = helper(root.left, root.val);
        int right = helper(root.right, root.val);
        max = Math.max(max, left + right);
        if(val == root.val) return Math.max(left, right) + 1;

        return 0;
    }
}

相關文章