当前位置:网站首页>leetcode-6116:计算布尔二叉树的值
leetcode-6116:计算布尔二叉树的值
2022-07-21 23:16:00 【菊头蝙蝠】
题目
题目连接
给你一棵 完整二叉树 的根,这棵树有以下特征:
- 叶子节点 要么值为 0 要么值为 1 ,其中 0 表示 False ,1 表示 True 。
- 非叶子节点 要么值为 2 要么值为 3 ,其中 2 表示逻辑或 OR ,3 表示逻辑与 AND 。
计算 一个节点的值方式如下:
- 如果节点是个叶子节点,那么节点的 值 为它本身,即 True 或者 False 。
- 否则,计算 两个孩子的节点值,然后将该节点的运算符对两个孩子值进行 运算 。
返回根节点 root 的布尔运算值。
完整二叉树 是每个节点有 0 个或者 2 个孩子的二叉树。
叶子节点 是没有孩子的节点。
示例 1:
输入:root = [2,1,3,null,null,0,1]
输出:true
解释:上图展示了计算过程。
AND 与运算节点的值为 False AND True = False 。
OR 运算节点的值为 True OR False = True 。
根节点的值为 True ,所以我们返回 true 。
示例 2:
输入:root = [0]
输出:false
解释:根节点是叶子节点,且值为 false,所以我们返回 false 。
解题
方法一:后序遍历
/** * 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:
bool dfs(TreeNode* root){
if(root->val==0) return false;
if(root->val==1) return true;
bool left=dfs(root->left);
bool right=dfs(root->right);
if(root->val==2){
return left||right;
}
else if(root->val==3){
return left&&right;
}
return true;
}
bool evaluateTree(TreeNode* root) {
return dfs(root);
}
};
边栏推荐
- 面试题 05.07. 配对交换
- [MySQL]数据库基础操作
- One bite of Stream(9)
- (iccv-2021) transfeid: Target Recognition Based on transformer
- [mysql] basic database operations
- mySQL基本函数
- 一个合约能存储多少数据?
- "New energy + energy storage" starts from the digital twin, Tupu will make smart power to the extreme
- One bite of Stream(8)
- 老薛主机磁盘空间满了怎么办
猜你喜欢
PMP practice once a day | don't get lost in the exam -7.21
service(lb) 和管理的pod
【MySQL必知必会】 存储过程 | 游标
What if Lao Xue's host disk space is full
(Applied intelligence-2022) transgait: gait recognition and ensemble transformer based on multimodality
window 编译生成darknet (cuda11.1+opencv4.5+vs2019)
webservice接口测试
老薛主机磁盘空间满了怎么办
QT program packaging and publishing method (using the official windeployqt tool)
Recordrtc video recording, playback, screenshot, Download
随机推荐
ERP系统在元器件贸易企业中的应用
It's a holiday. I need to read books carefully
uniapp常用的生命周期
Privacy-Preserving Generative Deep Neural Networks Support Clinical Data Sharing
win10如何设置锁屏后不熄屏
Pyhton crawls the primary and secondary website pages and saves the crawled image information locally
[mysql] basic database operations
224. 基本计算器-递归法
2022/07/18------顺时针打印矩阵
JVM类加载和垃圾回收
Elemen when clicking, modify the playback index of the walking lantern
service(lb) 和管理的pod
《性能之巅第2版》阅读笔记(五)--Disks监测
【C】信息管理系统/通讯录通用模板(介绍静态、动态、文件三个版本)
2022/07/19----栈的压入、弹出序列;表示数值的字符串
Common management problems and solutions in automation equipment manufacturing industry
RecordRTC的视频录制,回放,截图,下载
[advanced C language] learning about flexible arrays
Addition, deletion, query and modification of [mdsql] table (Advanced)
Mysql8 stored procedure generates calendar table and exception handling