LeetCode OJ(110. Balanced Binary Tree)

来源:互联网 发布:mac电脑怎么弄VPN 编辑:程序博客网 时间:2024/06/04 20:15

题目:
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.

用的递归方法,分别递归地求出左右子树的高度,再进行比较。

/** * Definition for a binary tree node. * 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;        int Left = Height(root->left);        int Right = Height(root->right);        if (abs(Left - Right) <= 1)          return (isBalanced(root->left) && isBalanced(root->right));        else          return false;    }    int Height(TreeNode *root)    {        if (root == NULL )          return 0;        else        {        if (root->left == NULL )          return Height(root->right) + 1;        else if (root->right == NULL)          return Height(root->left) + 1;        else{         int LeftH = Height(root->left);        int RightH = Height(root->right);        return LeftH > RightH ? LeftH + 1: RightH + 1;        }        }    }};

可见这种方法的效率并不是很高。

1 0
原创粉丝点击