题解 | #统计每个月兔子的总数#

统计每个月兔子的总数

https://www.nowcoder.com/practice/1221ec77125d4370833fd3ad5ba72395

import java.util.Scanner;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        // 注意 hasNext 和 hasNextLine 的区别
        while (in.hasNextInt()) { // 注意 while 处理多个 case
            int mounth = in.nextInt();
            TreeNode tree = new TreeNode();
            tree.setValue(1);
            TreeNode treeNode = createTree(mounth, mounth, tree);
            int count = countNum(treeNode, 0);
            System.out.println(count);
        }
    }

    public static TreeNode createTree(int mounth, int initMounth, TreeNode tree) {
        TreeNode leftNode = new TreeNode();
        TreeNode righttNode = new TreeNode();
        int n = initMounth - mounth;
        if (n == initMounth - 1) {
            return tree;
        }
        if (tree.getValue() != 0) {
            leftNode.setValue(0);
        } else {
            leftNode.setValue(1);
        }
        if (n > 0 && tree.getValue() != 0) {
            righttNode.setValue(1);
            tree.setRightNode(createTree(mounth - 1, initMounth, righttNode));
        }

        tree.setLeftNode(createTree(mounth - 1, initMounth, leftNode));
        return tree;

    }

    public static int countNum(TreeNode tree, int count) {
        if (tree.getValue() == 1) count++;
        if (tree.getLeftNode() != null) {
            count = countNum(tree.getLeftNode(), count);
        }
        if (tree.getRightNode() != null) {
            count = countNum(tree.getRightNode(), count);
        }
        return count;
    }
}

class TreeNode {
    private int value;
    private TreeNode leftNode;
    private TreeNode righttNode;

    public TreeNode() {
        this.leftNode = null;
        this.righttNode = null;
        this.value = 0;
    }

    public TreeNode(TreeNode leftNode, TreeNode righttNode, int value) {
        this.leftNode = leftNode;
        this.righttNode = righttNode;
        this.value = value;
    }

    public TreeNode getLeftNode() {
        return this.leftNode;
    }
    public TreeNode getRightNode() {
        return this.righttNode;
    }
    public int getValue() {
        return this.value;
    }

    public void setLeftNode(TreeNode leftNode) {
        this.leftNode = leftNode;
    }
    public void setRightNode(TreeNode righttNode) {
        this.righttNode = righttNode;
    }
    public void setValue(int value) {
        this.value = value;
    }

}
/**

 */

将空间与时间复杂的拉满的奇怪解法

全部评论

相关推荐

点赞 收藏 评论
分享
牛客网
牛客企业服务