码迷,mamicode.com
首页 > 编程语言 > 详细

Java for LeetCode 222 Count Complete Tree Nodes

时间:2015-06-15 18:19:37      阅读:144      评论: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 2h nodes inclusive at the last level h.

解题思路:

计算完全二叉树节点,直接递归会TLE,一个不错的思路是判断是否为满二叉树,然后进行递归,JAVA实现如下:

    public int countNodes(TreeNode root) {
        if(root==null)
        	return 0;
        int leftHeight=1,rightHeight=1;
        TreeNode temp=root.left;
        while(temp!=null){
        	temp=temp.left;
        	leftHeight++;
        }
        temp=root.right;
        while(temp!=null){
        	temp=temp.right;
        	rightHeight++;
        }
        if(leftHeight==rightHeight)
        	return (1<<leftHeight)-1;
        return countNodes(root.left)+countNodes(root.right)+1;
    }

 

Java for LeetCode 222 Count Complete Tree Nodes

标签:

原文地址:http://www.cnblogs.com/tonyluis/p/4578779.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!