边工作边刷题:70天一遍leetcode: day 17-2

Balanced Binary Tree

这题用recursive方法做非常trivial就不说了。试试怎么用itarative的方法,基本就是postorder traversal,局部子树的height可以存在结点map里。在访问结点的时候更新。
postorder iterative traversal的记忆法:第一个if是pre在上层,第二个if是pre是cur的left,最后的else是访问和出栈。

# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution(object):
    def isBalanced(self, root):
        """
        :type root: TreeNode
        :rtype: bool
        """
        if not root: return True
        stk = [root]
        pre = None
        hmap = {}
        while stk:
            cur = stk[-1]
            if not pre or pre.left==cur or pre.right==cur:
                if cur.left:
                    stk.append(cur.left)
                elif cur.right:
                    stk.append(cur.right)
            elif cur.left==pre:
                if cur.right:
                    stk.append(cur.right)
            else:
                stk.pop()
                lh,rh = 0,0
                if cur.left:
                    lh = hmap[cur.left]
                if cur.right:
                    rh = hmap[cur.right]
                if abs(lh-rh)>1: return False
                hmap[cur]=1+max(lh,rh)
            pre = cur
        
        return True
                
            
原文地址:https://www.cnblogs.com/absolute/p/5677882.html