zoukankan      html  css  js  c++  java
  • 剑指offer 平衡二叉树

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

    分析:首先理解什么是平衡二叉树。平衡二叉树具有以下性质:它是一 棵空树或它的左右两个子树的高度差的绝对值不超过1,并且左右两个子树都是一棵平衡二叉树。

    很明显可以用递归解决。

    解法一:

     1 class Solution {
     2 public:
     3     int depth(TreeNode *pRoot) {
     4         if (pRoot == nullptr) {
     5             return 0;
     6         }
     7         int left = depth(pRoot->left);
     8         int right = depth(pRoot->right);
     9         return max(left, right) + 1;
    10     }
    11     bool IsBalanced_Solution(TreeNode* pRoot) {
    12         if (pRoot == nullptr) {
    13             return true;
    14         }
    15         int left = depth(pRoot->left);
    16         int right = depth(pRoot->right);
    17         return (abs(left - right) <= 1 && IsBalanced_Solution(pRoot->left) && IsBalanced_Solution(pRoot->right));
    18     }
    19 };

    上述解法的不足在于在计算上层节点的时候,他会反复计算下层节点的深度,增加了时间复杂度,于是有了后序遍历的解法,先判断两个子树是否为平衡二叉树,是的话返回深度,否则标记为1.

    解法二:后序遍历

     1 class Solution {
     2 private:
     3     int getdepth(TreeNode *pRoot) {
     4         if (pRoot == NULL) {
     5             return 0;
     6         }
     7         int left = getdepth(pRoot->left);
     8         if (left == -1) {
     9             return -1;
    10         }
    11         int right = getdepth(pRoot->right);
    12         if (right == -1) {
    13             return -1;
    14         }
    15         return abs(left - right) > 1 ? -1 : 1 + max(left, right);
    16     }
    17 public:
    18     bool IsBalanced_Solution(TreeNode* pRoot) {
    19         return getdepth(pRoot) != -1;
    20     }
    21 };
  • 相关阅读:
    机器学习的几个知识点记录(转)
    mysql缓存、存储引擎
    特性选择、特征抽取阅读记录
    聚类、降维、文本处理阅读记录
    标准化、正则化阅读记录
    广播变量、累加器、collect
    实现Map-side Join和Reduce-side Join(转)
    MySQL数据库迁移(转)
    “数据迁移”考虑
    QT的信号和槽
  • 原文地址:https://www.cnblogs.com/qinduanyinghua/p/10474361.html
Copyright © 2011-2022 走看看