博文中会简要介绍Leetcode P0250题目分析及解题思路。
“Count Univalue Subtrees”是一道中等难度的题目
Given the root of a binary tree, return the number of uni-value subtrees.
A uni-value subtree means all nodes of the subtree have the same value.
Example 1:
Input: root = [5,1,5,5,5,null,5] Output: 4
以下是Java的题解代码实现。
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public int countUnivalSubtrees(TreeNode root) {
this.dfs(root);
return this.count;
}
private int count = 0;
private final int NULL = Integer.MIN_VALUE;
private final int NON_UNI = Integer.MAX_VALUE;
private int dfs(TreeNode curr) {
if (curr == null)
return Integer.MIN_VALUE;
int left = this.dfs(curr.left);
int right = this.dfs(curr.right);
if ((left == NULL || left == curr.val)
&& (right == NULL || right == curr.val)) {
this.count += 1;
return curr.val;
}
else {
return NON_UNI;
}
}
}
以下是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 countUnivalSubtrees(TreeNode* root) {
_Dfs(root);
return count_;
}
private:
int count_ = 0;
int _Dfs(TreeNode *curr) {
if (curr == nullptr) {
return INT_MIN;
}
int left = _Dfs(curr->left);
int right = _Dfs(curr->right);
if ((left == INT_MIN || left == curr->val)
&& (right == INT_MIN || right == curr->val)) {
count_ += 1;
return curr->val;
}
else {
return INT_MAX;
}
}
};