Leetcode: isBalanced
来源:互联网 发布:ad7606 Linux 335x 编辑:程序博客网 时间:2024/05/27 00:50
/** * 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) { // Start typing your C/C++ solution below // DO NOT write int main() function if(root==NULL) return true; if(abs(height(root->left)-height(root->right))>1) return false; else return isBalanced(root->left)&&isBalanced(root->right); } int height(TreeNode* node){ if(node==NULL) return 0; return max(height(node->left),height(node->right))+1; }};