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);
	}
};
 
posted @ 2019-12-25 11:05  尚修能的技术博客  阅读(100)  评论(0编辑  收藏  举报