【balanced-binary-tree】

Given a binary tree, determine if it is height-balanced.

For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1.



判斷給定的二叉樹是否爲平衡二叉樹

思路:因爲平衡二叉樹要求左右子樹的深度差值不超過1

這裏先實現一個輔助函數,計算二叉樹的深度;

最後採用遞歸的思想來完成;


class Solution {
public:
	bool isBalanced(TreeNode*  root)
	{
		if (root==NULL)
		{
			return true;
		}

		int left = help(root->left);
		int right = help(root->right);

		if (left-right>=-1 && left-right<=1)
		{
			if (isBalanced(root->left) && isBalanced(root->right))
			{
				return true;
			}
		}

		return false;
	}

	int help(TreeNode* root)
	{
		if (root==NULL)
		{
			return 0;
		}

		if (root->left==NULL && root->right==NULL)
		{
			return 1;
		}

		return max(help(root->left), help(root->right)) + 1;
	}
};


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章