1. 程式人生 > >【leetCode】 Balanced Binary Tree python版實現

【leetCode】 Balanced Binary Tree python版實現

原題連結

實現原理解析

該題比較簡單,主要思想是遞迴的判斷左右子樹的高度不大於1即可,注意異常處理

python程式碼實現

class Solution(object):
    def isBalanced(self, root):
        """
        :type root: TreeNode
        :rtype: bool
        """
        if root is None:
            return True

        elif (abs(self.height(root.left) - self.height(root.right)) >= 1
): return False else: return (self.isBalanced(root.left) and self.isBalanced(root.right)) def height(self, root): """ :param root: TreeNode :return: int """ if root is None: return 0 elif (root.left is None
and root.right is None): return 1 elif root.right is None: return 1 + self.height(root.left) elif root.left is None: return 1 + self.height(root.right) else: return 1 + max(self.height(root.left), self.height(root.right))