Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save miklund/b82fa0c82c65c8b570f05089b9ba5578 to your computer and use it in GitHub Desktop.
Save miklund/b82fa0c82c65c8b570f05089b9ba5578 to your computer and use it in GitHub Desktop.
2016-05-25-left-rotate-a-binary-tree-in-javascript
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);
};
var Expression = function(content, left, right) {
this.content = content;
this.left = left;
this.right = right;
// ERROR: this is not assignable
this = leftRotate(this);
};
new Expression('-',
new Value(1),
new Expression('+',
new Value(2),
new Expression('-',
new Value(3),
new Expression('+',
new Value(4),
new Value(5))
)
)
);
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