• C++版


    剑指offer 面试题39:判断平衡二叉树

    提交网址:  http://www.nowcoder.com/practice/8b3b95850edb4115918ecebdf1b4d222?tpId=13&tqId=11192

    时间限制:1秒       空间限制:32768K      参与人数:2481


    题目描述

    输入一棵二叉树,判断该二叉树是否是平衡二叉树。
    分析:
    平衡二叉树定义


    递归解法 AC代码:
    #include<iostream>
    #include<vector>
    using namespace std;
    struct TreeNode{
        int val; 
        TreeNode *left; 
        TreeNode *right; 
        TreeNode(int x) : val(x), left(NULL), right(NULL) {} 
    }; 
    class Solution {
    public:
    	int getHeight(TreeNode *root)
    	{
    		if(root==NULL) return 0;
    		int lh=getHeight(root->left);
    		int rh=getHeight(root->right);
    		int height=(lh<rh)?(rh+1):(lh+1);  // 记住:要加上根节点那一层,高度+1 
    		return height;
    	}
        bool IsBalanced_Solution(TreeNode* pRoot) {
    		if(pRoot==NULL) return true;
    		int lh=getHeight(pRoot->left);
    		int rh=getHeight(pRoot->right);
    		if(lh-rh>1 || lh-rh<-1)	return false;
    		else return (IsBalanced_Solution(pRoot->left) && IsBalanced_Solution(pRoot->right)); // 继续递归判断	
        }
    };
    // 以下为测试 
    int main()
    {
    	Solution sol;      
        TreeNode *root = new TreeNode(1);  
        root->right = new TreeNode(2);  
        root->right->left = new TreeNode(3);      
        bool res=sol.IsBalanced_Solution(root); 
        cout<<res<<" ";
        return 0; 
    }

    LeetCode 110. Balanced Binary Tree
    Total Accepted: 111269 Total Submissions: 326144 Difficulty: Easy


    提交网址: https://leetcode.com/problems/balanced-binary-tree/

    Given a binary tree, determine if it is height-balanced.

    For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1.


    AC代码:

    class Solution {
    public:
    	int getHeight(TreeNode *root)
    	{
    		if(root==NULL) return 0;
    		int lh=getHeight(root->left);
    		int rh=getHeight(root->right);
    		int height=(lh<rh)?(rh+1):(lh+1);  // 记住:要加上根节点那一层,高度+1 
    		return height;
    	}
        bool isBalanced(TreeNode *root) {
    		if(root==NULL) return true;
    		int lh=getHeight(root->left);
    		int rh=getHeight(root->right);
    		if(lh-rh>1 || lh-rh<-1)	return false;
    		else return (isBalanced(root->left) && isBalanced(root->right)); // 继续递归判断	
        }
    };




  • 相关阅读:
    摘金奇缘在线观看迅雷下载
    无敌破坏王2:大闹互联网在线观看
    神奇动物:格林德沃之罪电影在线观看
    你好,之华
    毒液:致命守护者
    apache 通过ajp访问tomcat多个站点
    docker使用大全 tomcat安装
    Log4j2 + Maven的配置文件示例详解
    centos7 设置tomcat自启动
    nginx多站路由配置tomcat
  • 原文地址:https://www.cnblogs.com/enjoy233/p/10408797.html
Copyright © 2020-2023  润新知