https://leetcode.com/contest/leetcode-weekly-contest-52/problems/longest-univalue-path/
[Implementation idea]: It is the same as longest path of a tree but with limitation. http://www.geeksforgeeks.org/diameter-of-a-binary-tree/ For Diameter of a Binary Tree, we need to recursively find out the height H() of sub-tree rooted at left & right child for each node. Then the answer is the node with max(H(node->left) + H(node->right)) + 1. For this case, an additional limit is the definition height H'(). It needs to be the same value to it's left or right child now. If not so, H'(node) is 0. Recursively calculate H'() for each node within the target tree. The answer is max(H'(node->left) + H'(node->right)) + 1 . #include <iostream> #include <set> #include <vector> #include <unordered_map> #include <limits.h> using namespace std; /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(i...
留言
張貼留言