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 difference of every node's two subtrees is not more than 1
.
Define a function for deep recursive traversal. Obtain the heights of the left and right subtrees of a node, in other words, define a function to obtain the height of the tree. When obtaining the heights of the left and right subtrees, compare whether the left and right subtrees are balanced. First, define the target variable target
, and then define the deep recursive traversal dfs
function. In the function, if the node does not exist, return 0
. Then comes the pruning part. If an unbalanced position has already been found, there is no need to continue traversing down. After that, define l
as the height of the left subtree, r
as the height of the right subtree, then compare, if the height difference between the left and right subtrees is greater than 1
, then it is deemed as not a balanced binary tree, assign target
to false
, and then return the height of the higher subtree of the left and right subtree +1
, execute dfs
deep recursive traversal, and return target
when done.