zoukankan      html  css  js  c++  java
  • [LintCode] Binary Tree Flipping

    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.

    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  


    Think Out Loud


    For a given node n whose left child is not null, we do the following changes.

    n.left.left = n.right;

    n.left.right = n;

    n.left = null;

    n.right = null.

    The new root after flipping is the leftmost node in the original tree.

    We can solve this recursively bottom up. Solving it top down is more complicated because we need the top nodes to access 

    the down nodes. Changing the top nodes makes this process a lot harder.

    O(n) runtime, O(H) space, H is the max depth of the give binary tree.



  • 相关阅读:
    php_l3arning_notes_3
    php_l3arning_notes_2
    php_l3arning_notes_1
    从 HTTP 到 HTTPS 再到 HSTS
    WSGI&ASGI
    WSGI 介绍
    什么是multipart/form-data请求
    SSH 端口转发
    Redis与RabbitMQ作为消息队列的比较
    数据库索引,到底是什么做的?
  • 原文地址:https://www.cnblogs.com/lz87/p/7478954.html
Copyright © 2011-2022 走看看