110. Balanced Binary Tree
Easy

Given a binary tree, determine if it is height-balanced.

For this problem, a height-balanced binary tree is defined as:

a binary tree in which the left and right subtrees of every node differ in height by no more than 1.

 

Example 1:

Given the following tree [3,9,20,null,null,15,7]:

    3
   / \
  9  20
    /  \
   15   7

Return true.

Example 2:

Given the following tree [1,2,2,3,3,null,null,4,4]:

       1
      / \
     2   2
    / \
   3   3
  / \
 4   4
这个题很明显是用DFS做,问题在于深度信息怎么传递,本来我想着在TreeNode中加一个变量信息
但这样明显有违题意,所以代码中采用了新的函数return直接返回深度或者-1,返回-1并不代表深度,只是
表示程序结束了。此外还是设置了一个类内全局变量来表示,这个题的延伸或者说目前的简单之处就在于
他只问你是否平衡而不需要问具体深度,所以只要用一个变量表示平衡,然后判断当数值不平衡时,改变变量即可
class TreeNode(object):
    def __init__(self,x):
        self.val=x
        self.left=None
        self.right=None
        
class Solution(object):
    def isBalanced(object,root):
        self.balanced=True
        def height(root):
            if not root or not self.balanced:
                return -1
            l=height(root.left)
            r=height(root.right)
            if abs(l-r)>1:
                self.balanced=False
                return -1
            return max(l,r)+1
        height(root)
        return self.balanced

 

 
111. Minimum Depth of Binary Tree
Easy

Given a binary tree, find its minimum depth.

The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node.

Note: A leaf is a node with no children.

Example:

Given binary tree [3,9,20,null,null,15,7],

    3
   / \
  9  20
    /  \
   15   7

return its minimum depth = 2.


这几道题的设计者真的有心了,整个放在一起也十分合适,都是树的专题,基本树的那些问题,都离不开,DFS,BFS,我也难得对这些算法自己能看出来,何时该用什么了,这道题是算到最近子节点的距离,和上一个算二叉树是否平衡的很像,但是比他简单一点,本来以为变换就是把上一题的最大改成最小,其实不然,bug在于如果根节点有个空子树,直接算会把他也作为长度算在内,但其实他的位置并没有子节点,所以没有意义,因此必须判断空来避免这种情况

我们时常感觉某种情况似曾相识,但是似是而非远远不够,我们应该尽量把生活精确起来,大部分人的生活就是批发市场,我们应该尽力把生活装进天平和量杯。

比如:相似——》简单了,难了?相同点在何,不同呢?用的知识点是哪些

刻苦——》达成了哪些成就,在什么时间里干了什么

好多人说时间表和计划没有用,比如本兔兔,但我觉得这是自己没动脑。这两者其实就是在把生活装进量杯

生活过的好坏是能力,你知道自己过的好坏是智力

posted on 2019-11-12 08:56  黑暗尽头的超音速炬火  阅读(174)  评论(0)    收藏  举报