Skip to content

Instantly share code, notes, and snippets.

@Guseyn
Last active April 9, 2019 16:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Guseyn/0510e4005f5372df7d215488a2cc1deb to your computer and use it in GitHub Desktop.
Save Guseyn/0510e4005f5372df7d215488a2cc1deb to your computer and use it in GitHub Desktop.
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