110. 平衡二叉树

https://leetcode-cn.com/problems/balanced-binary-tree/

解法一:递归

后序遍历,对root的左右子树递归求左右子树高,然后计算root的高=左右较高者+1。若左右之差大于1,全局flag为false

class Solution:
    def isBalanced(self, root: TreeNode) -> bool:
        self.flag = True
        self.helper(root)
        return self.flag
    
    def helper(self, root):
        if not root:    #递归出口
            return 0
        lh = self.helper(root.left)    #递归求左子树高
        rh = self.helper(root.right)    #递归求右子树高
        if abs(lh - rh) > 1:    #若发现不平衡
            self.flag = False
        return max(lh, rh) + 1

js

var isBalanced = function(root) {
    var helper = function(root) {
        if (root === null) {
            return 0
        }
        let lh = helper(root.left)
        let rh = helper(root.right)
        if (Math.abs(lh - rh) > 1) {
            flag = false
        }
        return Math.max(lh, rh) + 1
    }
    let flag = true
    helper(root)
    return flag

最后更新于