zoukankan      html  css  js  c++  java
  • 剑指 Offer 55

    题目描述

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

    示例1:
    给定二叉树 [3,9,20,null,null,15,7]

        3
       / 
      9  20
        /  
       15   7
    

    返回 true

    示例2:
    给定二叉树 [1,2,2,3,3,null,null,4,4]

           1
          / 
         2   2
        / 
       3   3
      / 
     4   4
    

    返回 false

    限制:

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

    来源:力扣(LeetCode)
    链接:https://leetcode-cn.com/problems/ping-heng-er-cha-shu-lcof

    代码实现

    /**
     * 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(!root)   return true;
            int leftDepth = getDepth(root->left);
            int rightDepth = getDepth(root->right);
            if(abs(leftDepth - rightDepth) > 1) return false;
            return isBalanced(root->left) && isBalanced(root->right);
        }
        int getDepth(TreeNode* root) {
            if(!root)    return 0;
            int leftDepth = getDepth(root->left);
            int rightDepth = getDepth(root->right);
            return (leftDepth > rightDepth) ? (leftDepth + 1) : (rightDepth + 1);
        }
    };
    

    思路解析

    • 递归实现:若左子树平衡,右子树平衡,且左右子树深度差小于1,则整树平衡。
  • 相关阅读:
    HDU 1198
    HDU 1863
    HDU 1879
    HDU 1233
    HDU 1232
    HDU 1829
    HDU 2473
    hdu 1829 A Bug's Life
    hdu 3038 How Many Answers Are Wrong
    hdu 1198 Farm Irrigation
  • 原文地址:https://www.cnblogs.com/xqmeng/p/13633622.html
Copyright © 2011-2022 走看看