【C++】 ——判斷一棵樹是否爲平衡二叉樹的兩種方法

判斷一棵樹是否爲平衡二叉樹
在這裏插入圖片描述
思路一:根據求樹的深度的方法,依次得到每個節點左子樹和右子樹的高度,再次計算每個節點其左右高度差是否滿足小於等於1,若都滿足返回真,若不滿足返回假

class Solution {
public:
    int GetDepth(TreeNode* proot)
    {
        if(proot==NULL)
            return 0;
        int leftDepth=1+GetDepth(proot->left);
        int rightDepth=1+GetDepth(proot->right);
        return leftDepth>rightDepth?leftDepth:rightDepth;
    }
    bool IsBalanced_Solution(TreeNode* pRoot) 
    {
        if(pRoot==NULL)
            return true;
        int left=GetDepth(pRoot->left);
        int right=GetDepth(pRoot->right);
        if(abs(left-right)>1)
            return false;
        return (IsBalanced_Solution(pRoot->left)&&
        IsBalanced_Solution(pRoot->right));
    }
    
};

思路二:

bool Isbalanced(TreeNode * root,int &Deepth)
{
	if (!root)
	{
		Deepth = 0;
		return true;
	}
	int left_depth, right_depth;
	if (Isbalanced(root->left, left_depth) && Isbalanced(root->right, right_depth))
	{
		int diff = left_depth - right_depth;
		if (diff <= 1 && diff >= -1)
		{
			Deepth = 1 + ((left_depth > right_depth) ? left_depth : right_depth);
			return true;
		}
	}
	return false;

}
bool IsBlancedTree(TreeNode* root)
{
	int Deepth = 0;
	return Isbalanced(root, Deepth);
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章