Java for LeetCode 222 Count Complete Tree Nodes

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

 

posted @ 2015-06-15 17:39  TonyLuis  阅读(541)  评论(0编辑  收藏  举报