-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbinarytreeinvertion.kl
More file actions
51 lines (41 loc) · 1000 Bytes
/
binarytreeinvertion.kl
File metadata and controls
51 lines (41 loc) · 1000 Bytes
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
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
// Define a binary tree node
class TreeNode {
init(value) {
this.value = value;
this.left = nil;
this.right = nil;
}
}
// Function to invert a binary tree
fun invertTree(node) {
if (node == nil) {
return nil;
}
// Swap the left and right children
var temp = node.left;
node.left = node.right;
node.right = temp;
// Recursively invert the left and right subtrees
invertTree(node.left);
invertTree(node.right);
return node;
}
// Helper function to print the tree in-order (for testing)
fun printInOrder(node) {
if (node != nil) {
printInOrder(node.left);
print node.value;
printInOrder(node.right);
}
}
// Example usage
var root = TreeNode(1);
root.left = TreeNode(2);
root.right = TreeNode(3);
root.left.left = TreeNode(4);
root.left.right = TreeNode(5);
print "Original tree in-order:";
printInOrder(root);
invertTree(root);
print "Inverted tree in-order:";
printInOrder(root);