T1:leetcode.2331 计算布尔二叉树的值
解析:
// struct TreeNode {
// int val;
// TreeNode* right;
// Treenode* left;
// TreeNode(val): val(val), left(nullptr), right(nullptr) {}
// TreeNode(int x, TreeNode* left, TreeNode* right): val(x), left(left), right(right) {}
// };
class Solution {
public:
bool isLeaf(TreeNode* node) {
return !node->left && !node->right;
}
bool evaluateTree(TreeNode* root) {
if (isLeaf(root)) return root->val;
if (root->val == 2) {
int result = 0;
if (root->left) {
result |= evaluateTree(root->left);
}
if (root->right) {
result |= evaluateTree(root->right);
}
return result;
}
int result = 1;
if (root->left) {
result &= evaluateTree(root->left);
}
if (root->right) {
result &= evaluateTree(root->right);
}
return result;
}
};
T2:leetcode.951 翻转等价二叉树
class Solution {
public:
bool flipEquiv(TreeNode* root1, TreeNode* root2) {
if (!root1 && !root2) return true;
if (!root1 && root2) return false;
if (!root2 && root1) return false;
if (root1->val != root2->val) return false;
if (flipEquiv(root1->right, root2->right) && flipEquiv(root1->left, root2->left)) return true;
if (flipEquiv(root1->right, root2->left) && flipEquiv(root1->left, root2->right)) return true;
return false;
}
};