Saturday, September 30, 2017
687. Longest Univalue Path
int len(TreeNode* node, int pa, int& mx) { // pa is the value of parent node
if(!node) return 0;
int l = len(node->left, node->val, mx);
int r = len(node->right, node->val,mx);
mx = max(mx, l+r);
if(node->val == pa) return 1+max(l,r);
else return 0;
}
int longestUnivaluePath(TreeNode* root) {
if(!root) return 0;
int mx = 0;
// root doesn't have parent node, pick any value that is different
len(root, root->val-1, mx);
return mx;
}
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment