完全二叉树的节点个数 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);
    }

猜你喜欢

转载自www.cnblogs.com/TIMHY/p/9700321.html