1. 程式人生 > >[leetcode]156.Binary Tree Upside Down顛倒二叉樹

[leetcode]156.Binary Tree Upside Down顛倒二叉樹

process png asi pre OS erl div inpu mea

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].

題意:

將一棵樹,按照一種方式上下顛倒

思路:

Need save the tree information before changing the tree structure

技術分享圖片

Now, the basic idea is to go though from the original root (1), make root’s left child (2) as newParent whose left child will be the original root’s right child (3) and right child will be the original root (1). After that, you set new root to root.left (2)

, 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);
 5         root.left.left = root.right;
 6         root.left.right = root;
 7         root.left = null ; 
 8         root.right = null;
 9         return newNode;
10     }
11 }

[leetcode]156.Binary Tree Upside Down顛倒二叉樹