码迷,mamicode.com
首页 > 其他好文 > 详细

Count Complete Tree Nodes ——LeetCode

时间:2015-06-25 13:43:02      阅读:81      评论: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
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!