zoukankan      html  css  js  c++  java
  • [leetcode]156.Binary Tree Upside Down颠倒二叉树

    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.

    Input: [1,2,3,4,5]
    
        1
       / 
      2   3
     / 
    4   5
    
    Output: return the root of the binary tree [4,5,2,#,#,3,1]
    
       4
      / 
     5   2
        / 
       3   1 

    Confused what [4,5,2,#,#,3,1] means? Read more below on how binary tree is serialized on OJ.

    The serialization of a binary tree follows a level order traversal, where '#' signifies a path terminator where no node exists below.

    Here's an example:

       1
      / 
     2   3
        /
       4
        
         5

    The above binary tree is serialized as [1,2,3,#,#,4,#,#,5].

    题意:

    将一棵树,按照一种方式上下颠倒

    Solution1: Tree + Recursion

    Need save the tree information before changing the tree structure

    Now, the basic idea is to go though from the original root (2), make root’s left child(4)  as newParent whose left child will be the original root’s right child (5) and right child will be the original root (2). After that, you set new root to root.left (5), and process it in the same way.

    代码:

     1 class Solution {
     2     public TreeNode upsideDownBinaryTree(TreeNode root) {
     3         if(root == null || root.left == null) return root;
     4         TreeNode newNode = upsideDownBinaryTree(root.left); // newNode最后要返回,所以找到、存下来后,就不再动了
     5         root.left.left = root.right;// 这里为何不是newNode.left = root.left ?
     6         root.left.right = root;
     7         root.left = null ; 
     8         root.right = null;
     9         return newNode;
    10     }
    11 }
  • 相关阅读:
    iOS多线程与网络开发之NSURLCache
    NEFU 117-素数个数的位数(素数定理)
    UISegmentedControl 的使用
    C++使用ADO存取图片
    王立平-- Swift
    浮生猫绘——落入平一的精灵
    BZOJ 1692: [Usaco2007 Dec]队列变换 [后缀数组 贪心]
    POJ2774 Long Long Message [后缀数组]
    BZOJ 2119: 股市的预测 [后缀数组 ST表]
    BZOJ 1717: [Usaco2006 Dec]Milk Patterns 产奶的模式 [后缀数组]
  • 原文地址:https://www.cnblogs.com/liuliu5151/p/9227161.html
Copyright © 2011-2022 走看看