代码随想录算法训练营 | 博客打卡
题目链接:leetcode 110. 平衡二叉树
注:仅为个人笔记,难以细致且通俗。
左右子树高度差不超过1。
先区分一下高度与深度的区别
一直递进到二叉树的最深处,在归返的时候依次加一,就能把二叉树当前节点的高度计算出来了。
func getHeight(root *TreeNode) int {
if root == nil {
// 触底反弹
return 0
}
lh := getHeight(root.Left)
rh := getHeight(root.Right)
return max(lh, rh) + 1 // 返回的是节点的高度
}
由于要判断是否为平衡二叉树,也就是左右子树高度差不能超过 1 。那就需要再增加判断逻辑,只要发现高度差超过 1 的情况,就标记起来。
func getHeight (node *TreeNode) int {
if node == nil {