leecode 解题总结:110. Balanced Binary Tree

来源:互联网 发布:数据库实用教程孙飞显 编辑:程序博客网 时间:2024/05/23 01:13
#include <iostream>#include <stdio.h>#include <vector>using namespace std;/*问题: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.分析:题目给定一颗二叉树,判定该二叉树是否是高度平衡的。所谓平衡的是指任意两个子树的高度之间的高度只差的绝对值<=1。举例:    3  1   2        4这个树是平衡的。     3  1      8 2 4   13      14这棵树不是平衡的可以这样,需要求出任意子树的高度,然后比较leftHeight - rightHeight对于当前结点,先判断其左子树是否平衡,如果左子树不平衡,肯定不是;判定右子树是否平衡,如果右子树不平衡,不是。在左右子树都平衡的前提下,计算左右子树的高度之差的绝对值,如果绝对值>1,不是;否则就是正确的。里面的关键就是:计算的结果同时要包含一棵树是否平衡,以及平衡时该子树的高度是多少。求一颗子树的高度,之前是用根节点作为输入参数,如果当前结点为空,高度为0;否则返回: 左右子树高度的较大值 + 1报错:Input:[1,null,2,null,3]Output:trueExpected:false应该是高度那里计算错了。关键:1 这是程序员面试金典的一道题目。我想起来了。应该是如果不平衡直接返回-1,如果平衡,就返回真实的高度即左右子树高度的较大值+1。也就是说要充分利用计算的高度*/struct TreeNode {     int val;     TreeNode *left;     TreeNode *right;     TreeNode(int x) : val(x), left(NULL), right(NULL) {}};class Solution {public:int isBalanceTree(TreeNode* root){//如果当前结点为空,返回的高度为0,且返回是平衡的if(NULL == root){return 0;}//根节点不空,先判断左子树是否平衡int leftResult = isBalanceTree(root->left);//如果左子树不平衡,肯定不平衡if(-1 == leftResult){return -1;}int rightResult = isBalanceTree(root->right);if(-1 == rightResult){return -1;}//在左右子树都平衡的情况下,判断左右子树高度之差的绝对值如果>1,则不平衡int absHeight = abs(rightResult - leftResult);if(absHeight > 1){return -1;//不平衡返回-1}//如果平衡,就返回当前结点的实际高度else{return ( max( leftResult , rightResult) + 1 );}}    bool isBalanced(TreeNode* root) {//根节点为空,肯定是平衡if(!root){return true;}        int result = isBalanceTree(root);if(-1 == result){return false;}else{return true;}    }};void print(vector<int>& result){if(result.empty()){cout << "no result" << endl;return;}int size = result.size();for(int i = 0 ; i < size ; i++){cout << result.at(i) << " " ;}cout << endl;}void process(){ vector<int> nums; int value; int num; Solution solution; vector<int> result; while(cin >> num ) { nums.clear(); for(int i = 0 ; i < num ; i++) { cin >> value; nums.push_back(value); } }}int main(int argc , char* argv[]){process();getchar();return 0;}

0 0