I. Question
Determine whether the given binary tree is a balanced binary tree, that is, the depth difference of each node is not greater than 1
Ii. Analysis
We generally think of recursion for tree problems, and the same is true for this question. We only need to determine whether the left and right subtree of each node are balanced.
Recursion, recursion, recursion ......
/*** 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) {If (depthcheck (Root) = 0) return true; If (ABS (depthcheck (root-> left)-depthcheck (root-> right)> 1) return false; elsereturn isbalanced (root-> left) & isbalanced (root-> right);} int depthchec K (treenode * root) {If (! Root) return 0; int depthl = depthcheck (root-> left) + 1; int depthr = depthcheck (root-> right) + 1; return depthl> depthr? Depthl: depthr ;}};
Leetcode: balanced_binary_tree