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

    题目描述

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

    解题思路

    考虑用后序遍历的思想,再遍历过程中分别记录左右子树的高度,若左右子树均为平衡二叉树,则继续比较左右子树的高度差并记录此时的树高,若不大于1则返回true,否则返回false。

    代码

     1 class Solution {
     2 public:
     3     bool IsBalanced_Solution(TreeNode* pRoot) {
     4         if(!pRoot)
     5             return true;
     6         int depth=0;
     7         return Balanced(pRoot,depth);
     8     }
     9     bool Balanced(TreeNode* pRoot,int &depth){
    10         int left=0,right=0;
    11         bool isba=true;
    12         if(pRoot->left)
    13             isba=Balanced(pRoot->left,left);
    14         if(pRoot->right)
    15             isba&=Balanced(pRoot->right,right);
    16         if(!isba)
    17             return false;
    18         if(abs(left-right)>1)
    19             return false;
    20         depth=max(left,right)+1;
    21         return true;
    22     }
    23 };
  • 相关阅读:
    JSON
    vue中跳转页面逻辑
    生命周期的几个阶段
    vue学习大纲
    Vue留言 checked框案列
    Vue内容
    linux -- iptables
    linux --- DNS
    linux --- samba
    linux --- vsftp
  • 原文地址:https://www.cnblogs.com/wmx24/p/8888681.html
Copyright © 2011-2022 走看看