LeetCode 968. Monitoring Binary Tree

 

Idea: Divide the node into three states, 0 means the node is monitored, 1 means the node can be monitored but not monitored, 2 means the node cannot be monitored.

dfs recursively,

If the left and right nodes cannot be monitored, num+1, return means that the parent node of the left and right node is monitored, (only the parent node can be monitored to ensure that the two child nodes are monitored).

If the left or right child node is monitored, the return indicates that the parent node can be monitored, but there is no security monitoring.

otherwise. Return indicates that the node is not monitored.

int num = 0;
    public int minCameraCover(TreeNode root) {
        if(root==null)return 0;
        if(dfs(root)==2)num++;
        return num;
    }

    //节点共有三种状态,0:该节点安了监控,1:该节点能被监控,但没装监控,2:该节点没有被监控
    private int dfs(TreeNode root) {
        if(root==null)return 1;
        int left = dfs(root.left),right=dfs(root.right);
        if(left==2||right==2){
            num++;
            return 0;
        }else if(left==0 || right==0){
            return 1;
        }else {
            return 2;
        }
    }

 

Guess you like

Origin blog.csdn.net/weichi7549/article/details/108742410