【Lintcode】1317. Count Complete Tree Nodes

题目地址:

https://www.lintcode.com/problem/count-complete-tree-nodes/description

给定一棵complete二叉树,求其节点个数。

由于complete二叉树的左右子树必然分别是complete二叉树,所以考虑到可以用分治法。先用两个指针分别向左右两端走,看整个二叉树最左端点和最右端点的深度是否相等,如果相等,则说明是满二叉树,其节点个数可以用 ( 1 < < d e p t h ) 1 (1<<depth)-1 来计算;否则的话可以递归求解两个子树的节点个数然后汇总。代码如下:

public class Solution {
    /**
     * @param root: root of complete binary tree
     * @return: the number of nodes
     */
    public int countNodes(TreeNode root) {
        // write your code here
        if (root == null) {
            return 0;
        }
        
        TreeNode left = root, right = root;
        int lDepth = 0, rDepth = 0;
        while (left != null) {
            lDepth++;
            left = left.left;
        }
    
        while (right != null) {
            rDepth++;
            right = right.right;
        }
        
        if (lDepth == rDepth) {
            return (1 << lDepth) - 1;
        } else {
        	// 分治
            return countNodes(root.left) + countNodes(root.right) + 1;
        }
    }
}

class TreeNode {
    int val;
    TreeNode left, right;
    TreeNode(int x) {
        val = x;
    }
}

空间复杂度 O ( log n ) O(\log n) ,时间复杂度 O ( log 2 n ) O(\log^2n) 。空间复杂度容易知道是 O ( h ) = O ( log n ) O(h)=O(\log n) ,时间复杂度可以这么考虑:需要注意到,对于同一个递归深度,只有一边会继续递归,另一边会直接套用公式,所以最差的情况是递归的每一层都要去遍历一下深度,所以总时间复杂度是 O ( i = 1 h i ) = O ( h 2 ) = O ( log 2 n ) O(\sum_{i=1}^{h}i)=O(h^2)=O(\log^2n)

发布了387 篇原创文章 · 获赞 0 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/qq_46105170/article/details/105464291