题目:
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 than10000
nodes.
The height of the tree is not more than1000
.
解释:
题目很好理解,注意path的长度是边的个数,path可以不经过root。
不经过root怎么写???
和543. Diameter of Binary Tree(python+cpp)类似,这道题目就是求不一定经过root的最长的path的长度。只要当前结点的值和它孩子结点的值不一样,就把孩子结点的深度置0。但是注意一定要先遍历再判断,如果先判断再决定要不要遍历的话,那么只要孩子结点的值和父节点不一样,整个子树就都没有遍历,子树里面可能的答案也就没有上传了,如下错误写法:
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def longestUnivaluePath(self, root):
"""
:type root: TreeNode
:rtype: int
"""
self.max_path=0
def TreeDepth(root):
if root==None:
return 0
left_depth=0
right_depth=0
if root.left:
left_depth=TreeDepth(root.left) if root.left.val==root.val else 0
if root.right:
right_depth=TreeDepth(root.right) if root.right.val==root.val else 0
self.max_path=max(self.max_path,left_depth+right_depth)
return max(left_depth,right_depth)+1
TreeDepth(root)
return self.max_path
正确解法:
python代码:
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def longestUnivaluePath(self, root):
"""
:type root: TreeNode
:rtype: int
"""
self.max_path=0
def TreeDepth(root):
left_depth=0
right_depth=0
if root.left:
left_depth=TreeDepth(root.left)
if root.left.val!=root.val:
left_depth=0
if root.right:
right_depth=TreeDepth(root.right)
if root.right.val!=root.val:
right_depth=0
self.max_path=max(self.max_path,left_depth+right_depth)
return max(left_depth,right_depth)+1
if root:
TreeDepth(root)
return self.max_path
c++代码:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
int max_path=0;
int longestUnivaluePath(TreeNode* root) {
if (root)
TreeDepth(root);
return max_path;
}
int TreeDepth(TreeNode *root)
{
int left_depth=0;
int right_depth=0;
if(root->left)
{
left_depth=TreeDepth(root->left);
if(root->left->val!=root->val)
left_depth=0;
}
if(root->right)
{
right_depth=TreeDepth(root->right);
if(root->right->val!=root->val)
right_depth=0;
}
max_path=max(max_path,left_depth+right_depth);
return max(left_depth,right_depth)+1;
}
};
总结: