162.Longest Univalue Path(最长相同值的路径)

题目:

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.

注意:给定的二叉树不超过10000个节点。 树的高度不超过1000。

解答:

方法一:

 1 /**
 2  * Definition for a binary tree node.
 3  * public class TreeNode {
 4  *     int val;
 5  *     TreeNode left;
 6  *     TreeNode right;
 7  *     TreeNode(int x) { val = x; }
 8  * }
 9  */
10 class Solution {
11     public int longestUnivaluePath(TreeNode root) {
12         if(root==null) return 0;
13         int sub=Math.max(longestUnivaluePath(root.left),longestUnivaluePath(root.right));
14         return Math.max(sub,helper(root.left,root.val)+helper(root.right,root.val));
15     }
16     
17     public int helper(TreeNode node,int val){
18         if(node==null || node.val!=val) return 0;
19         return 1+Math.max(helper(node.left,val),helper(node.right,val));
20     }
21 }

 方法二:

 1 /**
 2  * Definition for a binary tree node.
 3  * public class TreeNode {
 4  *     int val;
 5  *     TreeNode left;
 6  *     TreeNode right;
 7  *     TreeNode(int x) { val = x; }
 8  * }
 9  */
10 class Solution {
11     int len=0;
12     public int longestUnivaluePath(TreeNode root) {
13         if(root==null) return 0;
14         helper(root,root.val);
15         return len;
16     }
17     
18     private int helper(TreeNode node,int val){
19         if(node==null) return 0;
20         int left=helper(node.left,node.val);
21         int right=helper(node.right,node.val);
22         len=Math.max(len,left+right);
23         if(val==node.val) return Math.max(left,right)+1;
24         return 0;
25     }
26 }

详解:

递归。

方法一思路:

判断root是否为空,为空返回0;

对左右子节点分别调用当前函数,取其中较大值保存到sub中,sub表示左右子树中最长的相同值路径。

sub和当前树的最长相同值路径比较,选取较大的即为结果。当前树的最长相同值路径是对左右子节点分别调用helper函数,返回值相加的结果和sub比较。

helper函数,如果当前节点值不等于父节点值,则返回0,否则分别调用左右子节点的helper函数,其较大返回值加1(类似于求树的深度)

方法二思路:

判断root是否为空,为空返回0;

对左右子节点分别调用当前函数,取其中较大值保存到sub中,sub表示左右子树中最长的相同值路径。

当前结点和它左右子结点之间的关系:若它的左子节点和当前节点值相同,left+1,否则left=0;若它的右子节点和当前节点值相同,right+1,否则right=0;res=left+right

如果其左子结点存在且和当前节点值相同,则left自增1,否则left重置0;同理,如果其右子结点存在且和当前节点值相同,则right自增1,否则right重置0。然后用left+right来更新结果res。

posted @ 2018-09-12 20:20  chan_ai_chao  阅读(118)  评论(0编辑  收藏  举报