首页 > 其他 > 详细

Count Complete Tree Nodes ——LeetCode

时间:2015-06-25 13:42:49      阅读:106      评论:0      收藏:0      [点我收藏+]

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);
    }
}

 

Count Complete Tree Nodes ——LeetCode

原文:http://www.cnblogs.com/aboutblank/p/4599696.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!