zoukankan      html  css  js  c++  java
  • 边工作边刷题: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 	
        	
    
  • 相关阅读:
    composer使用git作为仓储
    monolog记录日志
    lumen laravel response对象返回数据
    lumen中间件 Middleware
    AcWing 901. 滑雪
    leetcode 34. 在排序数组中查找元素的第一个和最后一个位置
    acwing 902. 最短编辑距离
    ACWING 844. 走迷宫
    leetcode 5199. 交换字符串中的元素
    AcWing 836. 合并集合
  • 原文地址:https://www.cnblogs.com/absolute/p/5815666.html
Copyright © 2011-2022 走看看