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

    题目描述
    输入一棵二叉树,判断该二叉树是否是平衡二叉树。
     
    解题思路:平衡二叉树,对于每个根节点左右子树高度差小于等于1
     1 class Solution {
     2 public:
     3     int TreeDepth(TreeNode* pRoot)
     4     {
     5         if(pRoot == NULL)
     6             return 0;
     7         int nLeft = TreeDepth(pRoot->left);
     8         int nRight = TreeDepth(pRoot->right);
     9  
    10         return (nLeft > nRight)?(nLeft+1):(nRight+1);
    11     }
    12     bool IsBalanced_Solution(TreeNode* pRoot) {
    13         if(pRoot == NULL)
    14         {
    15             return true;
    16         }
    17         int nLeft = TreeDepth(pRoot->left);
    18         int nRight = TreeDepth(pRoot->right);
    19         int diff = nLeft-nRight;
    20         if(diff < -1 || diff > 1)
    21             return false;
    22         return IsBalanced_Solution(pRoot->left) && IsBalanced_Solution(pRoot->right);
    23     }
    24 };
  • 相关阅读:
    结构型模式(一) 适配器模式
    选择器
    CSS引入
    CSS语法
    CSS介绍
    HTML练习
    HTML标签嵌套规则(重点)
    HTML标签分类(重点)
    HTML标签属性
    body标签
  • 原文地址:https://www.cnblogs.com/qqky/p/7010302.html
Copyright © 2011-2022 走看看