剑指 Offer 55 - II. 平衡二叉树 - 力扣(LeetCode)

剑指 Offer 55 - II. 平衡二叉树 - 力扣(LeetCode)

题目描述

输入一棵二叉树的根节点,判断该树是不是平衡二叉树。如果某二叉树中任意节点的左右子树的深度相差不超过1,那么它就是一棵平衡二叉树。

限制:

1 <= 树的结点个数 <= 10000

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/ping-heng-er-cha-shu-lcof
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

题解

  1. 先序遍历 + 求树深度

这个是从上到下 判断每个结点

求树深度时,可以用map记录节点的高度,避免重复计算。但会增加内存开销。

时间复杂度为: O ( n l o g n ) O(nlogn) O(nlogn),最多需遍历n个结点,每个节点求高度为 l o g n logn logn

空间复杂度为: O ( n ) O(n) O(n)

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    unordered_map<TreeNode*, int>mark;
    bool isBalanced(TreeNode* root) {
        if(NULL == root){
            return true;
        }
        else{
            if(abs(getDepth(root->left) - getDepth(root->right)) <= 1){
                return isBalanced(root->left) && isBalanced(root->right);
            }
            else{
                return false;
            }
        }
    }

    int getDepth(TreeNode* root){
        if(NULL == root){
            return 0;
        }
        else{
            if(mark.find(root->left) == mark.end()){   
                mark[root->left] = getDepth(root->left);
            }
            if(mark.find(root->right) == mark.end()){
                mark[root->right] = getDepth(root->right);
            }
            return max(mark[root->left], mark[root->right]) + 1;
        } 
    }
};
  1. 后序遍历

从下至上,判断每个结点对应的树是否是平衡二叉树。

时间复杂度为: O ( n ) O(n) O(n),避免了重复计算。

空间复杂度为: O ( n ) O(n) O(n)

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
 /*

 */
class Solution {
public:
    
    bool isBalanced(TreeNode* root) {
        if(NULL == root){
            return true;
        }
        return getDepth(root) != -1;
    }

    int getDepth(TreeNode* root){
        if(NULL == root){
            return 0;
        }
        int leftDepth = getDepth(root->left);
        if(leftDepth == -1){
            return -1;
        }
        int rightDepth = getDepth(root->right);
        if(rightDepth == -1){
            return -1;
        }
        return abs(leftDepth - rightDepth) < 2?max(leftDepth, rightDepth) + 1:-1;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值