[LeetCode] 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.
解题思路:
递归分别求左子树和右子树的高度,然后比较,如果他们相差小于1,则返回高度,否则返回-1。最后root结点若返回-1则false,否则true。
/** * 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 depth(TreeNode *node) { if(node == NULL) return 0; int ld = 0, rd = 0; if(node -> left != NULL) ld = depth(node -> left); if(node -> right != NULL) rd = depth(node -> right); if(ld == -1 || rd == -1) return -1; if(abs(ld - rd) <= 1) return max(ld, rd) + 1; else return -1; } bool isBalanced(TreeNode *root) { // IMPORTANT: Please reset any member data you declared, as // the same Solution instance will be reused for each test case. if(depth(root) == -1) return false; else return true; } };