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

    题目描述

    输入一棵二叉树,判断该二叉树是否是平衡二叉树。
     
    解题思路:
    这里所说的平衡二叉树不要求是搜索树,平常意义上的二叉平衡树一般都是指平衡二叉搜索树。
    那么只需要判断任何一个节点的左右子树高度差是否大于1即可。
     
    class Solution {
    public:
        bool isBalanTree = true;
        int travalTree(TreeNode* root, int depth){
            if(root == NULL){
                return depth;
            }
            if(root->left == NULL && root->right == NULL){
                return depth;
            }
            int lh = depth;
            if(root->left != NULL){
                lh = travalTree(root->left, depth+1);
            }
            int rh = depth;
            if(root->right != NULL){
                 rh = travalTree(root->right, depth+1);
            }
           // cout<< "lh="<<lh<< " rh=" <<rh<<endl;
            if((lh == depth && rh - depth > 1) || (rh == depth && lh - depth > 1) || abs(lh-rh) >1){
                isBalanTree = false;
            }
            return max(lh, rh);
        }
        bool IsBalanced_Solution(TreeNode* pRoot) {
            if(pRoot == NULL) return true;
    
            travalTree(pRoot, 1);
    
            return isBalanTree;
        }
    };
    

      

  • 相关阅读:
    模糊匹配
    UPDATE SET FROM WHERE 续
    SQL SERVER 中row_number用法
    临时表和表变量
    镜像
    经典行列转换
    表记录查询最快查询方式
    NULL不是数值
    自增长值
    JSON
  • 原文地址:https://www.cnblogs.com/chengsheng/p/10680564.html
Copyright © 2011-2022 走看看