Skip to content

Instantly share code, notes, and snippets.

@anhulife
Created May 18, 2015 09:54
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 anhulife/4eeb2b7eca53e9cab075 to your computer and use it in GitHub Desktop.
Save anhulife/4eeb2b7eca53e9cab075 to your computer and use it in GitHub Desktop.
排序
function TreeNode(val){
this.val = val;
this.left = null;
this.right = null;
}
function addNodeToTree(root, val){
if (val < root.val){
if (!root.left){
root.left = new TreeNode(val);
} else {
addNodeToTree(root.left, val);
}
} else {
if (!root.right){
root.right = new TreeNode(val);
} else {
addNodeToTree(root.right, val);
}
}
}
function readTree(root){
var result = [];
if (root){
result = result.concat(readTree(root.left));
result.push(root.val);
result = result.concat(readTree(root.right));
}
return result;
}
function sortByTree(list){
var root = new TreeNode(list[0]);
list.slice(1).forEach(function (item) {
addNodeToTree(root, item);
});
return readTree(root);
}
sortByTree([1, 5, 3, 7, 6]);
@anhulife
Copy link
Author

使用二叉树进行排序

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment