二叉树灯饰
难度:
标签:
题目描述
English description is not available for the problem. Please switch to Chinese.
代码结果
运行时间: 305 ms, 内存: 31.7 MB
import java.util.*;
// 题目思路:
// 使用Java Stream API处理树结构较为复杂,因此这里的实现与传统Java实现类似。
// Stream API更适合处理集合而非树结构。
class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) { val = x; }
}
public class Solution {
public int minFlips(TreeNode root) {
return dfs(root);
}
private int dfs(TreeNode node) {
if (node == null) return 0;
int flips = 0;
// 左右子树的翻转次数
int leftFlips = dfs(node.left);
int rightFlips = dfs(node.right);
// 如果当前节点为1,则需要翻转
if (node.val == 1) {
flips += 1;
// 切换以当前节点为根的子树所有节点
toggleSubtree(node);
}
// 子节点的翻转次数加入总翻转次数
flips += leftFlips + rightFlips;
return flips;
}
private void toggleSubtree(TreeNode node) {
if (node == null) return;
node.val = 1 - node.val;
toggleSubtree(node.left);
toggleSubtree(node.right);
}
}
解释
方法:
The solution employs a dynamic programming approach using depth-first search (DFS) to determine the minimum number of switch operations needed to turn off all the lights in a binary tree. At each node, four states are computed, representing the minimum operations required for different configurations: 1) all lights on, 2) all lights off, 3) only the current node light on, and 4) only the current node light off. These states are computed based on the node's current state (light on or off) and the minimal operations required for its children's states. The recursive DFS function calculates the optimal switch operations for each state by combining results from left and right children and considering all possible switch actions at the current node.
时间复杂度:
O(n)
空间复杂度:
O(h) where h is the height of the tree, worst-case O(n)
代码细节讲解
🦆
解题思路中提到的四种状态具体是如何定义的?能否详细解释每个状态的具体意义?
▷🦆
在考虑转换状态时,为什么需要考虑`1 + l2 + r2`和`l1 + r1 + 1`这样的状态转换?这里的1代表什么操作?
▷🦆
解法中提到了利用深度优先搜索(DFS),请问这种方法在处理节点的子树状态时是如何确保所有情况都被考虑到的?
▷