【LeetCode】Balanced Binary Tree

来源:互联网 发布:sentinel ldk c 源码 编辑:程序博客网 时间:2024/05/17 22:00
/** * Definition for binary tree * struct TreeNode { *     int val; *     TreeNode *left; *     TreeNode *right; *     TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */class Solution {public:    int height(TreeNode *Node){if (Node == NULL)return 0;int lh = height(Node->left);int rh = height(Node->right);return lh > rh ? (lh + 1) : (rh + 1);}bool isBalanced(TreeNode *root){if (root == NULL)return true;int lheight, rheight;lheight = height(root->left);rheight = height(root->right);if (abs(lheight - rheight) > 1)return false;return isBalanced(root->left) && isBalanced(root->right);}};

0 0