判断是不是满二叉树

树形DP:

public static boolean isFull(TreeNode root) {
    
    
        if (root == null) {
    
    
            return true;
        }
        Info data = f(root);
        return data.nodes == (data.height << 1) - 1;
    }


    public static class Info {
    
    
        public int height;
        public int nodes;

        public Info(int height, int nodes) {
    
    
            this.height = height;
            this.nodes = nodes;
        }
    }

    public static Info f(TreeNode x) {
    
    
        if (x == null) {
    
    
            return new Info(0, 0);
        }
        Info leftData = f(x.left);
        Info rightData = f(x.right);
        int h = Math.max(leftData.height, rightData.height) + 1;
        int node = leftData.nodes + rightData.nodes + 1;
        return new Info(h, node);
    }

猜你喜欢

转载自blog.csdn.net/FYPPPP/article/details/115255755