222. Count Complete Tree Nodes

class Solution
{
public:
	int countNodes(TreeNode* root)
	{
		if (root == NULL)
		{
			return 0;
		}

		return GetTreeHeight(root);
	}
private:
	int GetTreeHeight(TreeNode* root)
	{
		if (root == NULL)
		{
			return 0;
		}

		int lth = 0;
		int rth = 0;  //right tree total height
		int lh = GetHight(root);
		int rh = GetHight(root->right) + 1;
		if (lh == rh)
		{
			//这棵树的左子树是满的
			lth = pow(2, lh - 1) - 1;
			return GetTreeHeight(root->right) + lth + 1;
		}
		else
		{
			//代表右子树是满的 递归解决左子树
			rth = pow(2, rh - 1) - 1;
			return GetTreeHeight(root->left) + rth + 1;
		}

	}

	/*遍历整棵树的左边界 获取树的高度*/
	int GetHight(TreeNode* root)
	{
		if (root == NULL)
		{
			return 0;
		}

		int hl = GetHight(root->left);

		return (hl + 1);
	}
};
 
原文地址:https://www.cnblogs.com/Manual-Linux/p/12095533.html