[LeetCode] Binary Tree Upside Down

156. Binary Tree Upside Down

Given the root of a binary tree, turn the tree upside down and return the new root.

You can turn a binary tree upside down with the following steps:

  1. The original left child becomes the new root.
  2. The original root becomes the new right child.
  3. The original right child becomes the new left child.

The mentioned steps are done level by level. It is guaranteed that every right node has a sibling (a left node with the same parent) and has no children.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
TreeNode* upsideDownBinaryTree(TreeNode* root) {
if(!root) return root;
TreeNode *res = root, *r = nullptr;
vector<TreeNode*> st;
while(res->left) {
auto nl = res->left;
res->left = r;
st.push_back(res);
r = res->right;
res = nl;
}
st.push_back(res);
res->left = r;
TreeNode *l = nullptr;
for(int i = 0; i < st.size(); i++) {
st[i]->right = l;
l = st[i];
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/07/22/PS/LeetCode/binary-tree-upside-down/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.