[LeetCode]Balanced Binary Tree

来源:互联网 发布:js excel文件流下载 编辑:程序博客网 时间:2024/06/05 09:30

题目:

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.

来源:https://oj.leetcode.com/problems/balanced-binary-tree/


思路:

判断二叉平衡树。

写一个BalancedHeight 函数用来计算某一节点的高度,然后对当前节点求其左右子树的高度差,最后递归检查其左右子树是否平衡。

C++ AC代码:

/** * Definition for binary tree * struct TreeNode { *     int val; *     TreeNode *left; *     TreeNode *right; *     TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */class Solution {public:    bool isBalanced(TreeNode *root) {        if ( root == NULL )    return true;if ( abs(BalancedHeight(root->left) - BalancedHeight(root->right)) > 1)    return false;return isBalanced(root->left) && isBalanced(root->right);    }int BalancedHeight (TreeNode* root){    if ( root == NULL ) return 0;int left = BalancedHeight (root->left);int right = BalancedHeight (root->right);return 1+max(left,right); }};

运行时间 60ms

0 0