250. Count Univalue Subtrees
Given a binary tree, count the number of uni-value subtrees.
A Uni-value subtree means all nodes of the subtree have the same value.
Example :
Input: root = [5,1,5,5,5,null,5]
5
/ \
1 5
/ \ \
5 5 5
Output: 4
方法1: dfs (postorder)
思路:
用一个bool来告诉父节点这个子树是不是unival,如果不是的话,父节点可以把这个false一直向上传递最终返回false。如果是的话,父节点需要再整合左右子树和它自己,再得出结论它是否也是univalue。而父节点所需要的信信息可以直接从cur -> val拿到,所以递归只需要返回bool就可以,同时keep一个供所有子树累加的global counter。
在当前节点审查时,先设立一个bool flag,它需要知道左子树是不是合格,右子树是不是合格,如果左右子树有值,每个子树都有一次机会将flag设为false。这个写法避免了复杂的条件嵌套(comment)。
class Solution {
public:
int countUnivalSubtrees(TreeNode* root) {
int result = 0;
univalueHelper(root, result);
return result;
}
bool univalueHelper(TreeNode* root, int & counter) {
if (!root) return true;
bool left_uni = univalueHelper(root -> left, counter);
bool right_uni = univalueHelper(root -> right, counter);
bool flag = true;
if (root -> left) flag = flag && (root -> left -> val == root -> val);
if (root -> right) flag = flag && (root -> right -> val == root -> val);
// bool selfconsistent = (T->left == nullptr || T->left->val == T->val) && (T-> right == nullptr || T->right->val == T->val);
counter += (left_uni && right_uni && flag);
return left_uni && right_uni && flag;
}
};
二刷:
class Solution {
public:
int countUnivalSubtrees(TreeNode* root) {
int res = 0;
uniHelper(root, res);
return res;
}
bool uniHelper(TreeNode* root, int & res) {
if (!root) return true;
bool left = uniHelper(root -> left, res);
bool right = uniHelper(root -> right, res);
bool flag = left && right;
flag &= (!root -> left || root -> left -> val == root -> val);
flag &= (!root -> right || root -> right -> val == root -> val);
res += (int) flag;
return flag;
}
};