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 };
  • 相关阅读:
    zlog 使用手册
    Contribution and Coding Style Guide Bullet Physics Library
    Windows系统读写ext2/3/4文件系统的工具「ext2fsd」
    blender svn
    c# 各个版本
    c# Looping with the foreach statement
    C# 9.0 and .NET 5 – Modern Cross-Platform Development
    我的常用博客
    qml通过stacklayout实现页面切换
    JSON解析-android平台(转)
  • 原文地址:https://www.cnblogs.com/qinduanyinghua/p/10474361.html
Copyright © 2011-2022 走看看