边工作边刷题:70天一遍leetcode: day 65

Invert Binary Tree

要点:这题很简单,一点点扩展是如果iterative做。pre-order还是post-order呢?根据recursion,因为既可以先reverse再递归,也可以先递归再reverse,所以没有区别。in-order可能也能用,不过会比较复杂。这题说明binary tree的题应该从从递归式想迭代的方法。

# 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 invertTree(self, root):
        """
        :type root: TreeNode
        :rtype: TreeNode
        """
        if not root: return root
        stk = [root]
        while stk:
            top = stk.pop()
            top.left, top.right = top.right, top.left
            if top.right:
                stk.append(top.right)
            if top.left:
                stk.append(top.left)
        
        return root
            
posted @ 2016-06-07 05:23  absolute100  阅读(87)  评论(0编辑  收藏  举报