zoukankan      html  css  js  c++  java
  • 平衡二叉树检查 牛客网 程序员面试金典 C++ Python

    平衡二叉树检查 牛客网 程序员面试金典 C++ Python

    • 题目描述

    • 实现一个函数,检查二叉树是否平衡,平衡的定义如下,对于树中的任意一个结点,其两颗子树的高度差不超过1。

    • 给定指向树根结点的指针TreeNode* root,请返回一个bool,代表这棵树是否平衡。

    C++

    /*
    struct TreeNode {
        int val;
        struct TreeNode *left;
        struct TreeNode *right;
        TreeNode(int x) :
                val(x), left(NULL), right(NULL) {
        }
    };*/
    
    
    class Balance {
    public:
    //rum:3ms memory:408k
        bool isBalance(TreeNode* root) {
            if (NULL == root) return true;
            if (NULL == root->left && NULL == root->right) return true;
            if (NULL != root->left && NULL == root->right)
                if(getTreeHeight(root->left) > 1) return false;
            if (NULL == root->left && NULL != root->right)
                if(getTreeHeight(root->right) >1) return false;
            return isBalance(root->left) && isBalance(root->right);
        }
        int getTreeHeight(TreeNode* root){
            if (NULL == root) return 0;
            return max(getTreeHeight(root->left),getTreeHeight(root->right))+ 1;
        }
    };

    Python

    # class TreeNode:
    #     def __init__(self, x):
    #         self.val = x
    #         self.left = None
    #         self.right = None
    class Balance:
        #run:27ms memory:5736k
        def isBalance(self, root):
            if None == root: return True
            if None == root.left and None == root.right: return True
            if None != root.left and None == root.right:
                if self.getTreeHeight(root.left) > 1: return False
            if None == root.left and None != root.right: 
                if self.getTreeHeight(root.right) > 1:return False
            return self.isBalance(root.left) and self.isBalance(root.right) + 1
                
        def getTreeHeight(self,root):
            if None == root: return 0
            return max(self.getTreeHeight(root.left),self.getTreeHeight(root.right)) + 1
    
  • 相关阅读:
    python -django 之第三方支付
    python 的排名,已经python的简单介绍
    第三方登录
    linux 基础命令
    JWT 加密
    Docker 简介
    中文分词库:结巴分词
    Django websocket 长连接使用
    jQuery截取字符串的几种方式
    Python 操作redis
  • 原文地址:https://www.cnblogs.com/vercont/p/10210322.html
Copyright © 2011-2022 走看看