# [LeetCode] 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.

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

```// Recursion
class Solution {
public:
TreeNode *upsideDownBinaryTree(TreeNode *root) {
if (!root || !root->left) return root;
TreeNode *l = root->left, *r = root->right;
TreeNode *res = upsideDownBinaryTree(l);
l->left = r;
l->right = root;
root->left = NULL;
root->right = NULL;
return res;
}
};```

```// Iterative
class Solution {
public:
TreeNode *upsideDownBinaryTree(TreeNode *root) {
TreeNode *cur = root, *pre = NULL, *next = NULL, *tmp = NULL;
while (cur) {
next = cur->left;
cur->left = tmp;
tmp = cur->right;
cur->right = pre;
pre = cur;
cur = next;
}
return pre;
}
};```

https://discuss.leetcode.com/topic/5961/easy-o-n-iteration-solution-java

https://discuss.leetcode.com/topic/40924/java-recursive-o-logn-space-and-iterative-solutions-o-1-space-with-explanation-and-figure

原文作者：Grandyang
原文地址: http://www.cnblogs.com/grandyang/p/5172838.html
本文转自网络文章，转载此文章仅为分享知识，如有侵权，请联系博主进行删除。