Skip to content

Instantly share code, notes, and snippets.

@Guseyn Guseyn/invertTree.js
Last active Apr 9, 2019

Embed
What would you like to do?
Invert Tree In Pure OO style
class TreeNode {
constructor (value, left, right) {
this.value = value
this.left = left
this.right = right
}
invert () {
if (!this.left && !this.right) {
return this
}
if (!this.left && this.right) {
this.left = this.right.invert()
} else if (!this.right && this.left) {
this.right = this.left.invert()
} else {
let tmp = this.left
this.left = this.right.invert()
this.right = tmp.invert()
}
return this
}
}
let tree = new TreeNode(4,
new TreeNode(2,
new TreeNode(1),
new TreeNode(3)
),
new TreeNode(7,
new TreeNode(6),
new TreeNode(9)
)
)
console.log(
'Input:\n',
tree
)
console.log(
'Output:\n',
tree.invert()
)
Input:
4
/ \
2 7
/ \ / \
1 3 6 9
Output:
4
/ \
7 2
/ \ / \
9 6 3 1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.