if node.left is None and node.right is None: # print depth, '<--' return depth if node.left is not None: queue.append(node.left) if node.right is not None: queue.append(node.right) depth += 1 return depth def min_depth_1(self, root): if root is None: return 0 return self.get_depth(root) def get_depth(self, root): if root is None: return sys.maxint if root.left is None and root.right is None: return 1 return 1 + min(self.get_depth(root.left), self.get_depth(root.right)) test_tree = BinaryTree.balanced_tree() test_tree.print_tree() print "the minimum Depth is: ", Solution().minDepth(test_tree.root) print "the minimum Depth is: ", Solution().min_depth(test_tree.root) print "the minimum Depth is: ", Solution().min_depth_1(test_tree.root)
""" :type root: TreeNode :rtype: bool """ return self.max_depth(root) != -1 def max_depth(self, root): if root is None: return 0 left_depth = self.max_depth(root.left) right_depth = self.max_depth(root.right) if abs(left_depth - right_depth) > 1 or left_depth == -1 or right_depth == -1: return -1 return max(left_depth, right_depth) + 1 # 用我自定义的Tree无法验证, 因为我是用None 代替"空", 但None也是一个节点. import BinaryTree testtree1 = BinaryTree.balanced_tree() testtree1.print_tree() print '1. is balanced?:\n', Solution().isBalanced(testtree1.root) print '\n' testtree2 = BinaryTree.not_balanced_tree() testtree2.print_tree() print '2. is balanced?:\n', Solution().isBalanced(testtree2.root)