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 subtreesEveryNode never differ by more than 1.
Determine whether a tree is a balanced binary tree.
Idea: typical recursion: Check whether the depth difference between the left and right subtree is less than or equal to 1 from the first root node, then, let's see if both the left and right course trees of the root node meet the requirements.
Code:
/*** Definition for binary tree * struct TreeNode {* int val; * TreeNode * left; * TreeNode * right; * TreeNode (int x): val (x ), left (NULL), right (NULL) {}*}; */class Solution {private: int maxdepth; public: void solve (TreeNode * root, int depth) {if (root = NULL) return; if (depth> maxdepth) maxdepth = depth; solve (root-> left, depth + 1); solve (root-> right, depth + 1);} int getDepth (TreeNode * root) {maxdepth = 0; solve (root, 1); return maxdepth;} bool isBalanced (TreeNode * root) {if (root = NULL) return true; int l, r; if (root-> left! = NULL) {l = getDepth (root-> left);} else {l = 0;} if (root-> right! = NULL) {r = getDepth (root-> right);} else {r = 0;} return abs (l-r) <= 1 & isBalanced (root-> left) & isBalanced (root-> right );}};
Balanced Binary Tree (Binary Tree DFS)