[Leetcode学习-java]Count Complete Tree Nodes(统计完全二叉树节点)

问题:

难度:easy

说明:

给出一个完全二叉树,然后你计算它的节点数量,树的节点都靠左,除了最后一个层,其它层都是填充完整的。

问题链接:https://leetcode.com/problems/count-complete-tree-nodes

输入案例:

Example:
Input: 
    1
   / \
  2   3
 / \  /
4  5 6
Output: 6

我的代码:

水题,题目给出提示可以用等比数列进行求和,只需要统计最后一层就行了。

等比数列公式,可以得出,有N层的话,那么除去最后一层有 2 ^ (N - 1) - 1个节点,N  >= 1。

class Solution {
    private int L = -1;
    public int countNodes(TreeNode root) {
        if(root == null) return 0;
        // 算出层级
        level(root);
        // 算出最后的一层数量
        int last = recurtion(root, 0);
        // 2 ^ N - 1 + last
        return (int)Math.pow(2, L) - 1 + last;
    }
    
    public void level(TreeNode root) {
        L ++;
        if(root.left != null) level(root.left);
    }
    
    public int recurtion(TreeNode root, int lev) {
        if(root == null) return 0;
        if(lev == L) return 1;
        return recurtion(root.left, lev + 1) + recurtion(root.right, lev + 1);
    }
}

当然也可以用bfs做,不过效率较低

class Solution {
    public int countNodes(TreeNode root) {
        ArrayList<TreeNode> list = new ArrayList<TreeNode>();
        if(root != null) list.add(root);
        int count = 0;
        int index = 0;
        
        // 这里我为了快不断地加,而不是remove,然后用index指针get元素
        while(index < list.size()) {
            count ++;
            TreeNode node = list.get(index ++);
            if(node.left != null) list.add(node.left);
            if(node.right != null) list.add(node.right);
        }
        
        return count;
    }
}

猜你喜欢

转载自blog.csdn.net/qq_28033719/article/details/106938253