二叉树的深度&判断一棵二叉树是否是平衡二叉树&110. Balanced Binary Tree

二叉树的深度

题目描述

输入一棵二叉树,求该树的深度。从根结点到叶结点依次经过的结点(含根、叶结点)形成树的一条路径,最长路径的长度为树的深度。

如果一棵树为空,那么它的深度为0。如果一棵树只有一个结点,它的深度为1。如果根结点只有做子树而没有右子树,那么树的深度应该是其左子树的深度加1;同样如果根结点只有右子树而没有左子树,那么树的深度就是其右子树的深度加1。如果既有左子树又有右子树,那么树的深度就是其左右子树中深度的较大值再加1。

int TreeDepth(TreeNode* pRoot)
    {
        if(!pRoot)
            return 0;
        int left = TreeDepth(pRoot->left);
        int right = TreeDepth(pRoot->right);

        return 1+(left>right?left:right);

    }

判断一棵二叉树是否是平衡二叉树

题目描述

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

思路一:
在遍历树的每个结点的时候,调用函数TreeDepth得到它的左右子树深度。如果每个结点的左右子树深度相差都不超过1,按照定义,它就是一棵平衡二叉树。

int TreeDepth(TreeNode* pRoot)
    {
        if(!pRoot)
            return 0;
        int leftDepth = TreeDepth(pRoot->left);
        int rightDepth = TreeDepth(pRoot->right);
        return leftDepth>rightDepth?leftDepth+1:rightDepth+1;
    }
    bool IsBalanced_Solution(TreeNode* pRoot) {
        if(!pRoot)
            return true;
        int leftDepth = TreeDepth(pRoot->left);
        int rightDepth = TreeDepth(pRoot->right);
        if(abs(leftDepth-rightDepth)>1)
            return false;
        return IsBalanced_Solution(pRoot->left) && IsBalanced_Solution(pRoot->right);

    }

思路一优化:

class Balance {
public:
    bool isBalance(TreeNode* root) {
        // write code here
        return checkHeight(root) == -1?false:true;
    }

    int checkHeight(TreeNode* root)
    {
        if(!root)
            return 0;


        int leftHeight = checkHeight(root->left);
        if(leftHeight == -1)
        {
            return -1;
        }

        int rightHeight = checkHeight(root->right);
        if(rightHeight == -1)
        {
            return -1;
        }

        if(abs(leftHeight-rightHeight) >1)
        {
            return -1;
        }
        else
        {
            return max(leftHeight,rightHeight)+1;
        }
    }
};

思路二:
如果我们用后序遍历的方式遍历二叉树的每个结点,那么在遍历到一个结点之前我们就已经遍历了它的左右子树。只要在遍历每个结点的时候记录它的深度,我们就可以一边遍历以便判断每个结点是不是平衡的。

bool isBalanced(TreeNode* pRoot,int& pDepth)
    {
        if(!pRoot)
        {
            pDepth = 0;
            return true;
        }

        int left=0;
        int right = 0;
        if(isBalanced(pRoot->left,left) && isBalanced(pRoot->right,right))
        {
            if(abs(left-right)<=1)
            {
                pDepth = 1+(left>right?left:right);
                return true;
            }

        }
        return false;
    }

    bool IsBalanced_Solution(TreeNode* pRoot) {
        int depth = 0;
        return isBalanced(pRoot,depth);

    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值