剑指55:二叉树的深度---平衡二叉树判定

题目描述1二叉树的深度

输入一棵二叉树,求该树的深度。从根结点到叶结点依次经过的结点(含根、叶结点)形成树的一条路径,最长路径的长度为树的深度。
思路:
每个根节点的深度都是左右子树最大值加1
/*
struct TreeNode {
	int val;
	struct TreeNode *left;
	struct TreeNode *right;
	TreeNode(int x) :
			val(x), left(NULL), right(NULL) {
	}
};*/
class Solution {
public:
    //递归实现 每个根节点的深度都是左右子树最大值加1
    int TreeDepth(TreeNode* pRoot)
    {
        if(!pRoot)
            return 0;
        int left = TreeDepth(pRoot->left);
        int right = TreeDepth(pRoot->right);
        return (left>right)?(left+1):(right+1);
    }
};

题目描述2:平衡二叉树

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

思路: 通过后序遍历可获得左右子树的深度情况,然后计算平衡因子,为了简化计算,需要用一个数值记录子树的深度。

class Solution {
public:
    bool IsBalanced_Solution(TreeNode* pRoot) {
        //默认无节点是平衡的
        int depth=0;
        return IsBalanced(pRoot,depth);
    }
    bool IsBalanced(TreeNode* pRoot,int& depth){
        //后序遍历,同时时刻记录当前节点作为根时的深度
        if(!pRoot)
            return true; 
        int left=0,right=0;
        if(IsBalanced(pRoot->left,left)&&IsBalanced(pRoot->right,right))  //后序遍历并统计左右子树各自的深度
        {
            int diff = right - left;
            if(diff>=-1&&diff<=1)
            {
                depth = 1 + (left>right?left:right);  //这个括号必须有 优先级   //每次在原有子树基础上比值和增1
                return true;
            }
        }
        return false;
    }
};


猜你喜欢

转载自blog.csdn.net/yanbao4070/article/details/80244391