Created
May 25, 2016 13:54
-
-
Save miklund/b82fa0c82c65c8b570f05089b9ba5578 to your computer and use it in GitHub Desktop.
2016-05-25-left-rotate-a-binary-tree-in-javascript
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
function leftRotate(node) { | |
var rightNode = node.right; | |
// right is a node and not a leaf | |
if (rightNode.nodeType === 'node') { | |
// copy node content | |
var content = node.content; | |
node.content = rightNode.content; | |
rightNode.content = content; | |
// left rotation | |
node.right = rightNode.right; | |
rightNode.right = rightNode.left; | |
rightNode.left = node.left; | |
node.left = rightNode; | |
leftRotate(rightNode); | |
} | |
}; | |
var Expression = function(content, left, right) { | |
this.content = content; | |
this.left = left; | |
this.right = right; | |
// left rotate this node down the tree | |
leftRotate(this); | |
}; |
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
var Expression = function(content, left, right) { | |
this.content = content; | |
this.left = left; | |
this.right = right; | |
// ERROR: this is not assignable | |
this = leftRotate(this); | |
}; |
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
new Expression('-', | |
new Value(1), | |
new Expression('+', | |
new Value(2), | |
new Expression('-', | |
new Value(3), | |
new Expression('+', | |
new Value(4), | |
new Value(5)) | |
) | |
) | |
); |
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
function leftRotate(node) { | |
var rightNode = node.right; | |
// right is a node and not a leaf | |
if (rightNode.nodeType === 'node') { | |
node.right = rightNode.left; | |
rightNode.left = node; | |
return leftRotate(rightNode); | |
} | |
return rightNode; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment