leetcode 968. 监控二叉树

image

贪心思想:尽量在父节点上放摄像头

用后序遍历,三种状态:

0: 无摄像头,并且没被覆盖
-1: 无摄像头,且被覆盖了
1: 有摄像头
class Solution {
    int num=0;

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

    int postOrder(TreeNode root){
        if(root==null) return -1;
        int left=postOrder(root.left),right=postOrder(root.right);
        if(left==-1&&right==-1) return 0;
        else if(left==0||right==0){
            num++;
            return 1;
        }else return -1;
    }
}
posted @ 2022-02-22 17:38  livingsu  阅读(32)  评论(0)    收藏  举报