题目大意:给你一棵二叉树,返回一条最长的路径,要求路径上所有的节点值都相同。
https://leetcode.com/problems/longest-univalue-path/description/
Problem:
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.
Idea:
DFS
Solution: Recursion
Time complexity: O(n)
Space complexity: O(n)
C++
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
// Author: Huahua // Runtime: 69 ms class Solution { public: int longestUnivaluePath(TreeNode* root) { if (root == nullptr) return 0; int ans = 0; univaluePath(root, &ans); return ans; } private: int univaluePath(TreeNode* root, int* ans) { if (root == nullptr) return 0; int l = univaluePath(root->left, ans); int r = univaluePath(root->right, ans); int pl = 0; int pr = 0; if (root->left && root->val == root->left->val) pl = l + 1; if (root->right && root->val == root->right->val) pr = r + 1; *ans = max(*ans, pl + pr); return max(pl, pr); } }; |
Java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
// Author: Huahua // Runtime: 12 ms class Solution { private int ans; public int longestUnivaluePath(TreeNode root) { if (root == null) return 0; this.ans = 0; univaluePath(root); return this.ans; } private int univaluePath(TreeNode root) { if (root == null) return 0; int l = univaluePath(root.left); int r = univaluePath(root.right); int pl = 0; int pr = 0; if (root.left != null && root.val == root.left.val) pl = l + 1; if (root.right != null && root.val == root.right.val) pr = r + 1; this.ans = Math.max(this.ans, pl + pr); return Math.max(pl, pr); } } |
Python3
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
""" Author: Huahua Runtime: 899 ms """ class Solution: def longestUnivaluePath(self, root): self.ans = 0 self._univaluePath(root) return self.ans def _univaluePath(self, root): if root is None: return 0 l = self._univaluePath(root.left) if root.left is not None else -1 r = self._univaluePath(root.right) if root.right is not None else -1 pl = l + 1 if l >= 0 and root.val == root.left.val else 0 pr = r + 1 if r >= 0 and root.val == root.right.val else 0 self.ans = max(self.ans, pl + pr) return max(pl, pr) |
Related Problems
请尊重作者的劳动成果,转载请注明出处!花花保留对文章/视频的所有权利。
如果您喜欢这篇文章/视频,欢迎您捐赠花花。
If you like my articles / videos, donations are welcome.
Be First to Comment