Count Complete Tree Nodes ——LeetCode

Given a complete binary tree, count the number of nodes.

Definition of a complete binary tree from Wikipedia:
In a complete binary tree every level, except possibly the last, is completely filled, and all nodes in the last level are as far left as possible. It can have between 1 and 2hnodes inclusive at the last level h.

题目大意:给定一个完全二叉树,返回这个二叉树的节点数量。

解题思路:一开始想着层次遍历,O(n),结果TLE,后来优化了下,采用递归的方式来做,总节点数等于1+左子树的数量+右子树的数量,因为是完全二叉树,所以对于子树是满二叉树的可以直接计算出结果并返回。

public class Solution {
    public int countNodes(TreeNode root) {
        if(root==null){
            return 0;
        }
        TreeNode left =root,right=root;
        int cnt = 0;
        while(right!=null){
            left=left.left;
            right=right.right;
            cnt++;
        }
        if(left==null){
            return (1<<cnt)-1;
        }
        return 1+countNodes(root.left)+countNodes(root.right);
    }
}
原文地址:https://www.cnblogs.com/aboutblank/p/4599696.html