2023每日刷题(六)
Leetcode—2331.计算布尔二叉树的值
递归实现代码
/*** Definition for a binary tree node.* struct TreeNode {* int val;* struct TreeNode *left;* struct TreeNode *right;* };*/
bool evaluateTree(struct TreeNode* root){struct TreeNode* p = root;if(p == NULL) {return NULL;} else if(p->left == NULL) {if(p->val == 0) {return false;} else {return true;}} bool left = evaluateTree(p->left);bool right = evaluateTree(p->right);if(p->val == 2) {return left || right;} else if(p->val == 3){return left && right;} else if(p->val == 0) {return false;} else {return true;}
}
运行结果
改良版代码
/*** Definition for a binary tree node.* struct TreeNode {* int val;* struct TreeNode *left;* struct TreeNode *right;* };*/
bool evaluateTree(struct TreeNode* root){if(!root->left) {return root->val;}return (root->val == 2 ? (evaluateTree(root->left) || evaluateTree(root->right)): (evaluateTree(root->left) && evaluateTree(root->right)));
}
运行结果
之后我会持续更新,如果喜欢我的文章,请记得一键三连哦,点赞关注收藏,你的每一个赞每一份关注每一次收藏都将是我前进路上的无限动力 !!!↖(▔▽▔)↗感谢支持!