1. 程式人生 > >前端面試題之手寫二叉排序樹

前端面試題之手寫二叉排序樹

前端面試題之手寫二叉排序樹

二叉排序樹:每個節點的左節點都比根節點小,右節點都比根節點大

function TreeNode(data, left, right) { //節點結構
    this.val = data;
    this.left = left;
    this.right = right;
}

function BST() { //二叉樹建構函式
    this.root = null; //預設是一顆空樹
    this.insert = function (data) { //新增節點功能
        var newNode = new TreeNode
(data, null, null); //首先構造一個二叉樹節點 if(!this.root) { //如果是一個空樹(空樹根節點是null),直接把這個節點變成根節點 this.root = newNode; }else { this.insertNode(this.root, newNode) //不是空樹的情況 } }; this.insertNode = function (root, newNode) { //首先判斷將要加入的節點和目前節點的大小 if(newNode.
val < root.val) { //如果比節點小 if(root.left === null) { //如果節點的左邊是null root.left = newNode; //直接新增到做節點 return; //返回 } this.insertNode(root.left, newNode); //如果節點的左邊不是空的(左邊已經存在節點了),那就把左邊的節點作為根節點遞迴 }else { //如果比節點大 if(root.right ===
null) { //如果節點的右邊是null root.right = newNode; //直接新增到做節點 return; //返回 } this.insertNode(root.right, newNode); //如果節點的右邊不是空的(左邊已經存在節點了),那就把左邊的節點作為根節點遞迴 } //遞迴到最後找到為null的結點把它新增就完事 } } var bst = new BST(); bst.insert(12); bst.insert(5); bst.insert(17); bst.insert(4); bst.insert(6); bst.insert(30); console.log(bst);

在這裡插入圖片描述