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

Binary Tree Upside Down

要点:

  • recursion反转如何做?两个要点,一是在递归之后反转link(因为先要通过原来的link到下一层),二是要一层层把最底层的root返回来。
  • iteration如何做?和recursion不同,不是反转下一层的,而是这一层的。这是因为和递归不同,下一层还没做,要保留下一层到下下一层的连接。
    • 在反转这一层时,要记录下一层next,同时连接的是上一层pre。pre初始为None
    • pre要记录两个:结点本身和preright,因为pre的连接改变的时候,left/right都变了,而right是给cur用的
    • https://repl.it/CjWT/1
# Given a binary tree where all the right nodes are either leaf nodes with a sibling 
# (a left node that shares the same parent node) or empty, flip it upside down and 
# turn it into a tree where the original right nodes turned into left leaf nodes. 
# Return the new root.
# 
# For example:
# Given a binary tree {1,2,3,4,5},
# 
#     1
#    / \
#   2   3
#  / \
# 4   5
# 
# return the root of the binary tree [4,5,2,#,#,3,1].
# 
#    4
#   / \
#  5   2
#     / \
#    3   1  
#

# 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 upsideDownBinaryTree(self, root):
        """
        :type root: TreeNode
        :rtype: TreeNode
        """
        pre, pre_right = None, None
        cur = root
        while cur:
            next_left, next_right = cur.left, cur.right
            cur.left, cur.right = pre_right, pre
            pre, pre_right = cur, next_right
            cur = next_left
        
        return pre 	
    	
posted @ 2016-08-03 19:01  absolute100  阅读(128)  评论(0编辑  收藏  举报