解题思路
递归解决这题,我们需要计算每个节点下的左右子树的高度,若不符合平衡二叉树则直接返回false。
总共会出现3种情况
当前节点为空,返回0
当前节点的左右子树不为平衡树,返回-1
左右子树高度的绝对值差>1返回-1
返回1 + max(左树,右树)
代码
Python
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 class Solution : def isBalanced (self, root: Optional [TreeNode] ) -> bool : if root is None : return True def getDepth (root ): if root is None : return 0 leftDepth = getDepth(root.left) if leftDepth == -1 : return -1 rightDepth = getDepth(root.right) if rightDepth == -1 : return -1 return -1 if abs (leftDepth - rightDepth) > 1 else 1 + max (leftDepth, rightDepth) return not (getDepth(root) == -1 )
C++
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 class Solution {public : bool isBalanced (TreeNode* root) { return !(getDepth (root) == -1 ); } int getDepth (TreeNode* root) { if (root == NULL ) return 0 ; int leftDepth = getDepth (root->left); int rightDepth = getDepth (root->right); if (leftDepth == -1 || rightDepth == -1 ) return -1 ; return abs (leftDepth - rightDepth) > 1 ? -1 : 1 + max (leftDepth, rightDepth); } };
Go
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 func isBalanced (root *TreeNode) bool { if root == nil { return true } return !(getDepth(root) == -1 ) } func getDepth (root *TreeNode) int { if root == nil { return 0 } leftDepth := getDepth(root.Left) rightDepth := getDepth(root.Right) if leftDepth == -1 || rightDepth == -1 { return -1 } if abs(leftDepth - rightDepth) > 1 { return -1 } else { return 1 + max(leftDepth, rightDepth) } } func abs (a int ) int { if a < 0 { return -a } return a } func max (a int , b int ) int { if (a >= b){ return a } return b }