687. Longest Univalue Path(python+cpp)
阿新 • • 發佈:2018-12-19
題目:
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 than1000
.
解釋: 題目很好理解,注意path的長度是邊的個數,path可以不經過root。 不經過root怎麼寫??? 和543. Diameter of Binary Tree(python+cpp)
# 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;
}
};
總結: