计算布尔二叉树的值【LC2331】
You are given the
root
of a full binary tree with the following properties:
- Leaf nodes have either the value
0
or1
, where0
representsFalse
and1
representsTrue
.- Non-leaf nodes have either the value
2
or3
, where2
represents the booleanOR
and3
represents the booleanAND
.The evaluation of a node is as follows:
- If the node is a leaf node, the evaluation is the value of the node, i.e.
True
orFalse
.- Otherwise, evaluate the node’s two children and apply the boolean operation of its value with the children’s evaluations.
Return the boolean result of evaluating the
root
node.A full binary tree is a binary tree where each node has either
0
or2
children.A leaf node is a node that has zero children.
吃饱饱喝饱饱学习习
-
思路:DFS
使用深度搜索,返回每颗子树的布尔值,每颗子树的布尔结果与其布尔操作有关,即父节点的值,因此递归函数需要传入父节点的值
-
实现
-
确定递归函数的参数和返回值
-
参数:当前节点root,父节点的值
-
返回值:boolean,该子树的计算结果
-
-
确定终止条件
- 当前节点是空时返回,当父节点为或操作时,返回
false
;当父节点为与操作时,返回true
;
- 当前节点是空时返回,当父节点为或操作时,返回
-
确定单层递归的逻辑
- 当节点是叶子节点时,根据值返回
true
和false
- 当节点不是叶子节点使,继续dfs搜索
- 当节点是叶子节点时,根据值返回
/** * 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 boolean evaluateTree(TreeNode root) { return dfs(root, 2); } public boolean dfs (TreeNode root, int pre){ if (root == null){ if (pre == 2) return false;// or else return true;// and } if (root.val == 2) { return dfs(root.left, 2) || dfs(root.right, 2); } else if (root.val == 3){ return dfs(root.left, 3) && dfs(root.right, 3); } return root.val == 1; } }
- 复杂度
- 时间复杂度:O(n)O(n)O(n)
- 空间复杂度:O(n)O(n)O(n)
-
-
优化:不需要记录父节点的值,二叉树为完整二叉树
class Solution { public boolean evaluateTree(TreeNode root) { if (root.left == null) { return root.val == 1; } if (root.val == 2) { return evaluateTree(root.left) || evaluateTree(root.right); } else { return evaluateTree(root.left) && evaluateTree(root.right); } } } 作者:力扣官方题解 链接:https://leetcode.cn/problems/evaluate-boolean-binary-tree/solutions/2091770/ji-suan-bu-er-er-cha-shu-de-zhi-by-leetc-4g8f/ 来源:力扣(LeetCode) 著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
- 复杂度
- 时间复杂度:O(n)O(n)O(n)
- 空间复杂度:O(n)O(n)O(n)
- 复杂度