完全二叉树的节点个数 Count Complete Tree Nodes

2018-09-25 16:36:25

问题描述:

问题求解:

单纯遍历了一遍,emmm,果然TLE。

解题思路就是比较左边树高度和右边树高度,如果相等,那么就是一个满二叉树,返回1 << h - 1即可,如果不是,则递归的计算左右子树的个数。

时间复杂度:O(logn * logn)

    public int countNodes(TreeNode root) {
        if (root == null) return 0;
        int l = leftHeight(root);
        int r = rightHeight(root);
        if (l == r) return (1 << l) - 1;
        else return 1 + countNodes(root.left) + countNodes(root.right);
    }
    
    private int leftHeight(TreeNode root) {
        if (root == null) return 0;
        return 1 + leftHeight(root.left);
    }
    
    private int rightHeight(TreeNode root) {
        if (root == null) return 0;
        return 1 + rightHeight(root.right);
    } 

 

2019-04-15 14:42:44

其实我根本不用管二叉树的种类,直接递归去计数就可以了,在log(n)的时间复杂度内完成,且速度完胜之前的解法。

Runtime: 0 ms, faster than 100.00% of Java online submissions for Count Complete Tree Nodes.

    public int countNodes(TreeNode root) {
        if (root == null) return 0;
        return countNodes(root.left) + countNodes(root.right) + 1;
    }

 

posted @ 2018-09-25 16:40  hyserendipity  阅读(278)  评论(0编辑  收藏  举报