天天看點

968. 監控二叉樹

968. 監控二叉樹

968. 監控二叉樹

題解

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public int minCameraCover(TreeNode root) {
        if (lrd(root) == 0) {
            res++;
        }
        return res;
    }

    int res=0;
    int lrd(TreeNode node) {

        if (node == null) {
            return 1;
        }
        int left=lrd(node.left);
        int right=lrd(node.right);
        if (left == 0 || right == 0) {
            res++;
            return 2;
        }
        if(left==1&&right==1){
            return 0;
        }
        if(left+right>=3){
            return 1;
        }

        return -1;
    }
}      

繼續閱讀