LeetCode Problem #687
Given a binary tree find the longest possible path with same node values. The length of the path is determined the number of edges between the node.
Example 1:
Input:
5
/ \
4 5
/ \ \
1 1 5
Output: 2
Example 2:
Input:
1
/ \
4 5
/ \ \
4 4 5
Output: 2
Solution in C++:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
int longestUnivaluePath(TreeNode* root) {
int maxi = 0;
longestCalUtil(root, maxi);
return maxi;
}
int longestCalUtil (TreeNode* node, int &maxi){
if(!node)
return 0;
int l = longestCalUtil(node->left, maxi);
int r = longestCalUtil(node->right, maxi);
int left_max = 0;
int right_max = 0;
if(node->left && node->left->val == node->val){
left_max = l + 1;
}
if(node->right && node->right->val == node->val){
right_max = r + 1;
}
maxi = max(maxi, left_max + right_max);
return max(left_max, right_max);
}
};
LeetCode Problem #111
Given a
binary tree find the minimum depth of the tree. The depth of root node is zero.
Solution in 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 minDepth(TreeNode* root) {if(!root)
return 0;
return Depth(root);
}
int Depth (TreeNode* root){if(!root)
return INT_MAX - 1;
if(!root->left && !root->right)
return 1;
return min(Depth(root->left), Depth(root->right)) + 1;
}
};
Comments
Post a Comment