Leetcode_110 _ Balanced Binary Tree, balancedbinarytree
Thank you for your reference. If you have any errors or questions, please leave a message to correct them. Thank you.
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.
Calculate the height of left and right subtree and determine whether the height difference between left and right subtree cannot exceed 1.
The depth of the tree is accumulated from the root node (its depth is 1) from top to bottom layer, and the height is from the leaf node (its height is 1) accumulated from bottom to top.
/** * Definition for binary tree * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */class Solution {private: bool balance = true; int height(TreeNode *root) { if(!balance) return -1; if(root==NULL) return 0; else { int left_height = height(root->left)+1; int right_height = height(root->right)+1; if( abs(left_height-right_height) > 1) balance = false; else return left_height>right_height ? left_height : right_height; } }public: bool isBalanced(TreeNode *root) { height(root); return balance; }};