zoukankan      html  css  js  c++  java
  • LeetCode 110. Balanced Binary Tree平衡二叉树 (C++)

    题目:

    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.

    Example 1:

    Given the following tree [3,9,20,null,null,15,7]:

        3
       / 
      9  20
        /  
       15   7

    Return true.

    Example 2:

    Given the following tree [1,2,2,3,3,null,null,4,4]:

           1
          / 
         2   2
        / 
       3   3
      / 
     4   4
    

    Return false.

    分析:

    给定一个二叉树,判断它是否是高度平衡的二叉树。

    一棵高度平衡二叉树定义为:一个二叉树每个节点的左右两个子树的高度差的绝对值不超过1。

    递归求解每个节点的左右两个子树的高度差的绝对值是否超过1即可,树的高度也是递归求解,返回左右子树最大值。

    程序:

    /**
     * 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 == nullptr) return true;
            return abs(height(root->left, 0)-height(root->right, 0)) <= 1 && isBalanced(root->left) && isBalanced(root->right);
        }
        int height(TreeNode* root, int h) {
            if(root == nullptr) return h;
            return max(height(root->left, h+1), height(root->right, h+1));
        }
    };
  • 相关阅读:
    Orchard学习 02、orchard 路由
    Orchard学习 01、orchard日志
    golang限制协程的最大开启数
    go爬取博客园
    go xpath 添加头部解析
    goadmin文档
    使用GoAdmin极速搭建golang应用管理后台
    Python GUI之tkinter窗口视窗教程大集合(看这篇就够了)转
    自定义推荐央视
    python爬虫 xpath
  • 原文地址:https://www.cnblogs.com/silentteller/p/10854504.html
Copyright © 2011-2022 走看看