Created
May 18, 2015 09:54
-
-
Save anhulife/4eeb2b7eca53e9cab075 to your computer and use it in GitHub Desktop.
排序
This file contains 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 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]); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
使用二叉树进行排序