(Java)leetcode-687 Longest Univalue Path (最長同值路徑)

題目描述

給定一個二叉樹,找到最長的路徑,這個路徑中的每個節點具有相同值。 這條路徑可以經過也可以不經過根節點。

注意:兩個節點之間的路徑長度由它們之間的邊數表示。

示例 1:

輸入:


              5
             / \
            4   5
           / \   \
          1   1   5

輸出:

2

示例 2:

輸入:

              1
             / \
            4   5
           / \   \
          4   4   5

輸出:

2
注意: 給定的二叉樹不超過10000個結點。 樹的高度不超過1000。

思路

參考(Java)leetcode-543 Diameter of Binary Tree(二叉樹的直徑)
依然採用 後序遍歷 ,用自下而上求路徑長度並更新最大值的思想,不同之處就是,本題需要先判斷值與父節點相同才能計算路徑長度。

代碼

class Solution {
	int longestLength = 0;
    public int longestUnivaluePath(TreeNode root) {
    	if (root == null) return 0;
    	calLength(root, root.val);
    	return longestLength;
    }

	private int calLength(TreeNode root, int target) {
		if (root == null) return 0;
		int left = calLength(root.left, root.val);
		int right = calLength(root.right, root.val);

		// 更新最長長度
		longestLength = Math.max(longestLength, left + right);

		// 返回值相等的路徑長度
		if (root.val == target) return Math.max(left, right) + 1 ;
		else return 0;
	}
}

在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章