剑指offer. 55-2 平衡二叉树

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接: https://blog.csdn.net/speargod/article/details/98796103

剑指offer. 55-2 平衡二叉树

题目描述:

输入一棵二叉树,判断该二叉树是否是平衡二叉树。

解题思路:

利用后序遍历二叉树的每个节点,同时在遍历每个节点的时候记录它的深度

代码:

class Solution {
public:
    bool IsBalanced_Solution(TreeNode* pRoot) {
        int depth;
        return isbalance(pRoot,&depth);
    }
	
	bool isbalance(TreeNode* pRoot, int *depth){
		if(!pRoot){
			*depth=0;
			return true;
		}
		int dL,dR;
		if(isbalance(pRoot->right,&dR) &&isbalance(pRoot->left,&dL) ){
			*depth=1+max(dR,dL);
			return abs(dR-dL)<=1;
		}
		//只有true的时候才需要设置depth 否则一路都是false
		return false;
	}
	
};

猜你喜欢

转载自blog.csdn.net/speargod/article/details/98796103
今日推荐