Skip to content

Commit 523e99f

Browse files
authored
Merge pull request akgmage#1794 from akgmage/dev
add invert tree in cpp and py
2 parents 7437a41 + 525ed33 commit 523e99f

File tree

2 files changed

+85
-0
lines changed

2 files changed

+85
-0
lines changed

Trees/Binary Trees/invert.cpp

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
// Invert Binary tree
2+
#include <iostream>
3+
4+
class BinaryTreeNode {
5+
public:
6+
int data;
7+
BinaryTreeNode* left;
8+
BinaryTreeNode* right;
9+
10+
BinaryTreeNode(int val) : data(val), left(nullptr), right(nullptr) {}
11+
};
12+
13+
BinaryTreeNode* invertTree(BinaryTreeNode* root) {
14+
if (root != nullptr) {
15+
root->left = invertTree(root->right);
16+
root->right = invertTree(root->left);
17+
}
18+
return root;
19+
}
20+
21+
BinaryTreeNode* invertTree2(BinaryTreeNode* root) {
22+
if (root != nullptr) {
23+
// swap the pointers in this node
24+
BinaryTreeNode* temp = root->left;
25+
root->left = root->right;
26+
root->right = temp;
27+
28+
invertTree2(root->left);
29+
invertTree2(root->right);
30+
}
31+
return root;
32+
}
33+
34+
int main() {
35+
// Example usage:
36+
// Construct a binary tree
37+
BinaryTreeNode* root = new BinaryTreeNode(1);
38+
root->left = new BinaryTreeNode(2);
39+
root->right = new BinaryTreeNode(3);
40+
root->left->left = new BinaryTreeNode(4);
41+
root->left->right = new BinaryTreeNode(5);
42+
43+
// Invert the binary tree using the first approach
44+
BinaryTreeNode* invertedRoot = invertTree(root);
45+
46+
// Invert the binary tree using the second approach
47+
BinaryTreeNode* invertedRoot2 = invertTree2(root);
48+
49+
// Additional code for printing or further usage...
50+
51+
return 0;
52+
}

Trees/Binary Trees/invert.py

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
# Invert Binary tree
2+
class BinaryTreeNode:
3+
def __init__(self, data):
4+
self.left = None
5+
self.data = data
6+
self.right = None
7+
8+
def invert_tree(root):
9+
if root:
10+
root.left, root.right = invert_tree(root.right), invert_tree(root.left)
11+
return root
12+
13+
def invert_tree2(root):
14+
if root is not None:
15+
# swap the pointers in this node
16+
root.left, root.right = root.right, root.left
17+
invert_tree2(root.left)
18+
invert_tree2(root.right)
19+
return root
20+
21+
# Example usage:
22+
# Assuming you have a binary tree
23+
root = BinaryTreeNode(1)
24+
root.left = BinaryTreeNode(2)
25+
root.right = BinaryTreeNode(3)
26+
root.left.left = BinaryTreeNode(4)
27+
root.left.right = BinaryTreeNode(5)
28+
29+
# Invert the binary tree using the first approach
30+
inverted_root = invert_tree(root)
31+
32+
# Invert the binary tree using the second approach
33+
inverted_root2 = invert_tree2(root)

0 commit comments

Comments
 (0)