110. Balanced Binary Tree

110. 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)从根节点开始得遍历会导致很多节点的多次遍历,代码如下:

 int treeDepth(TreeNode* root)
    {
        if(root == NULL)
            return 0;
        
        queue<TreeNode*> que;
        que.push(root);
        int countLevNodes = 1;
        int depth = 0;
        while(!que.empty())
        {
            TreeNode* temp = que.front();
            que.pop();
            countLevNodes--;
            if(temp->left != NULL)
                que.push(temp->left);
            if(temp->right != NULL)
                que.push(temp->right);
            if(countLevNodes == 0)
            {
                depth++;
                countLevNodes = que.size();
            }
        }
        
        return depth;
    }
    
    bool isBalanced(TreeNode* root) {
        if(NULL == root)
            return true;
        
        int left = treeDepth(root->left);
        int right = treeDepth(root->right);
        int diff = abs(left - right);
        if(diff > 1)
            return false;
        return isBalanced(root->left)&&isBalanced(root->right);
    }
(2)从后序开始遍历,使得很多节点的遍历只用遍历一次

采用的后续遍历的方式遍历二叉树的每一个节点的,在遍历到一个节点之前我们就已经遍历了它的左右子树。只要在遍历每个节点的时候记录它的深度(某一节点的深度等于

它到叶结点的路径的长度),我们就可以一边遍历一边判断每个节点是不是平衡的

bool isBalanced(TreeNode* root,int* pdepth)
    {
        if(NULL == root)
        {
            *pdepth = 0;
            return true;
        }
        
        int left,right;
        if(isBalanced(root->left,&left)&&isBalanced(root->right,&right))
        {
            int diff = left - right;
            if(abs(diff)<=1)
            {
                *pdepth = 1 + (left>right?left:right);
                return true;
            }
        }
        return false;
    }
    
    bool isBalanced(TreeNode* root) {
        int depth = 0;
        return isBalanced(root,&depth);//由于每一次调用该函数都要去改变depth的数值,所以depth为引用传递
    }

方法二、采用dfs的方法来计算每个节点的左右孩子节点的高度

int dfsHeight (TreeNode *root) {
        if(NULL == root)
            return 0;
        int leftHeight = dfsHeight(root->left);
        if(leftHeight == -1) return -1;
        int rightHeight = dfsHeight(root->right);
        if(rightHeight == -1) return -1;
        if (abs(leftHeight - rightHeight) > 1)  return -1;
        return max (leftHeight, rightHeight) + 1;
    }
    bool isBalanced(TreeNode* root) {
        return dfsHeight(root) != -1;
    }



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值