Last active
April 9, 2019 16:22
-
-
Save Guseyn/0510e4005f5372df7d215488a2cc1deb to your computer and use it in GitHub Desktop.
Invert Tree In Pure OO style
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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() | |
) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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