【題目】687. 最長同值路徑
給定一個二叉樹,找到最長的路徑,這個路徑中的每個節點具有相同值。 這條路徑可以經過也可以不經過根節點。
注意:兩個節點之間的路徑長度由它們之間的邊數表示。
示例 1:
輸入:
5
/ \
4 5
/ \ \
1 1 5
輸出:
2
示例 2:
輸入:
1
/ \
4 5
/ \ \
4 4 5
輸出:
2
注意: 給定的二叉樹不超過10000個結點。 樹的高度不超過1000。
【解題思路1】遞歸
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
int ans = 0;
public int longestUnivaluePath(TreeNode root) {
dfs(root);
return ans;
}
public int dfs(TreeNode root){
if(root == null){
return 0;
}
int left = dfs(root.left); //遞歸左右子樹
int right = dfs(root.right);
//初始化左右路徑與根結點想等的爲0
int arrowleft = 0, arrowright = 0;
//若左孩子和根結點值相同,向左的路徑就是孩子以下的最長路徑長度+1
if(root.left != null && root.left.val == root.val){
arrowleft = left + 1;
}
if(root.right != null && root.right.val == root.val){
arrowright = right + 1;
}
ans = Math.max(ans, arrowleft + arrowright);
//左右路徑只能選其一,所以返回最大的
return Math.max(arrowleft, arrowright);
}
}