您的位置:首页 > 产品设计 > UI/UE

leetcode 687. Longest Univalue Path

2018-01-04 18:04 435 查看

一 题目

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


二 .解析

一颗二叉树,找出一条最长的路径,在这个路径上,所有的节点值都相等,这最长的路径可以不通过root这个节点。不是求节点的个数 而是求长度。这道题需要用到递归,求出左子树的最长路径 ,有子树的最长路径。然后判断左子树值跟root值是否相等,右子树值跟root值是否相等。

三.代码

/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
private int result = 0;
public int longestUnivaluePath(TreeNode root) {
help(root);
return result;
}
public int help(TreeNode root){
if(root == null){
return 0;
}
int l = help(root.left); //左子树最长路径的的值
int r = help(root.right); //右子树最长路径的值
int left = 0, right = 0; //因为站在root的角度
if(root.left != null && root.val == root.left.val){//可以连在一个路径上
left = l + 1;
}
if(root.right != null && root.val == root.right.val){//可以连在一个路径上
right = r + 1;
}
result = Math.max(result,left + right);
return Math.max(left,right);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: