Javacript二叉樹常見算法實現及快速排序求第K大值

以前實習筆試的時候刷題一直用的java,也參考某篇文章寫過java版的二叉樹常見算法,由於立刻要轉正面試了,這幾天都在準備面試,就把以前的翻出來用javascript從新寫了一遍,二叉樹基本都是遞歸處理的,也比較簡單,就當作熱身。後面也寫了幾種常見的排序算法,並用快排求第K大值,另外若是以前java版的做者看到的話能夠留言,我會標明文章引用。javascript

Javacript二叉樹常見算法實現

節點構造函數和二叉樹構造函數

function Node(key) {
    this.key = key;
    this.left = null;
    this.right = null;
}
function binaryTree() {
    this.root = null;
}

插入節點生成二叉樹

binaryTree.prototype.insert = function(root, key) {
    var node = new Node(key);
    if (root === null) { //樹根節點爲空則將此節點做爲根節點
        this.root = node;
    } else if (node.key < root.key) { //小於左孩子節點則要麼做爲左子節點要麼遞歸插入左部門
        if (root.left === null) {
            root.left = node;
        } else {
            this.insert(root.left, key);
        }
    } else { //大於右孩子節點則要麼做爲右子節點要麼遞歸插入到右部分
        if (root.right === null) {
            root.right = node;
        } else {
            this.insert(root.right, key);
        }
    }
}

先序遍歷

//先序遍歷遞歸方法
binaryTree.prototype.preOrder = function(node) {
    if (node !== null) {
        console.log(node.key); //先打印當前結點
        this.inOrder(node.left); //打印左結點
        this.inOrder(node.right); //打印右結點
    }
}

//先序遍歷非遞歸方法
//首先將根節點入棧,若是棧不爲空,取出節點打印key值,而後依次取右節點和左節點入棧,依次重複
binaryTree.prototype.preOrder2 = function(node) {
    let stack = [];
    stack.push(node);
    while (stack.length > 0) {
        let n = stack.pop();
        console.log(n.key);
        if (n.right != null) {
            stack.push(n.right);
        }
        if (n.left != null) {
            stack.push(n.left);
        }
    }
}

中序遍歷

//中序遍歷遞歸方法
binaryTree.prototype.inOrder = function(node) {
    if (node !== null) {
        this.inOrder(node.left);
        console.log(node.key);
        this.inOrder(node.right);
    }
}

//中序遍歷非遞歸方法
//依次取左節點入棧直到左下角節點入棧完畢,彈出節點打印key,若是該節點有右子節點,將其入棧
binaryTree.prototype.inOrder2 = function(node) {
    let stack = [];
    while (node != null || stack.length) {
        if (node != null) {
            stack.push(node);
            node = node.left;
        } else {
            let n = stack.pop();
            console.log(n.key);
            node = n.right;
        }
    }
}

後序遍歷

binaryTree.prototype.postOrder = function(node) {
    if (node !== null) {
        this.inOrder(node.left);
        this.inOrder(node.right);
        console.log(node.key);
    }
}

求樹的深度

binaryTree.prototype.treeDepth = function(node) {
    if (node === null) {
        return 0;
    }
    let left = this.treeDepth(node.left);
    let right = this.treeDepth(node.right);
    return (left > right) ? (left + 1) : (right + 1);
}

判斷兩棵樹結構是否相同

binaryTree.prototype.structCmp = function(root1, root2) {
    if (root1 == null && root2 == null) { //根節點都爲空返回true
        return true;
    }
    if (root1 == null || root2 == null) { //根節點一個爲空一個不爲空返回false
        return false;
    }
    let a = this.structCmp(root1.left, root2.left); //都有孩子節點則遞歸判斷左邊是否是相同而且右邊也相同
    let b = this.structCmp(root1.right, root2.right);
    return a && b; //左子樹相同而且右子樹相同
}

獲得第k層節點個數

binaryTree.prototype.getLevelNum = function(root, k) {
    if (root == null || k < 1) {
        return 0;
    }
    if (k == 1) {
        return 1;
    }
    return this.getLevelNum(root.left, k - 1) + this.getLevelNum(root.right, k - 1); //從左子樹角度看,根節點第k層就是相對於左子樹k-1層,把左子樹右子樹k-1層相加便可
}

求二叉樹的鏡像

binaryTree.prototype.mirror = function(node) {
    if (node == null) return;
    [node.left, node.right] = [node.right, node.left]; //交換左右子樹並依次遞歸
    this.mirror(node.left);
    this.mirror(node.right);
}

最近公共祖先節點

binaryTree.prototype.findLCA = function(node, target1, target2) {
    if (node == null) {
        return null;
    }
    if (node.key == target1 || node.key == target2) { //若是當前結點和其中一個節點相等則當前結點爲公共祖先
        return node;
    }
    let left = this.findLCA(node.left, target1, target2);
    let right = this.findLCA(node.right, target1, target2);
    if (left != null && right != null) { //若是左右子樹都沒找到則目標節點分別在左右子樹,根節點爲其祖先
        return node;
    }
    return (left != null) ? left : right; // 找到的話返回
}

測試用

var tree = new binaryTree();
let arr = [45, 5, 13, 3, 23, 7, 111];
arr.forEach((node) => {java

tree.insert(tree.root, node);

});node

var tree2 = new binaryTree();
let arr2 = [46, 6, 14, 4, 24, 8, 112];
arr2.forEach((node) => {面試

tree2.insert(tree2.root, node);

});算法

tree.preOrder(tree.root);
tree.preOrder2(tree.root);
tree2.inOrder(tree2.root);
tree.inOrder2(tree.root);
let depth = tree.treeDepth(tree.root);
console.log(depth);
let isstructCmp = tree2.structCmp(tree.root, tree2.root);
console.log(isstructCmp);
let num = tree.getLevelNum(tree.root, 4);
console.log(num);
tree.mirror(tree.root);
tree.inOrder(tree.root);
let n = tree.findLCA(tree.root, 111, 3);
console.log(n);數組

快速排序求第K大值

快速排序

function quickSort(array) {
  if(array.length <= 1){
      return array;
  }
  let middle = Math.floor(array.length / 2)
  let pivot = array.splice(middle, 1);
  let left =[], right = [];
  for(let i = 0; i < array.length; i++) {
      if(array[i] < pivot) {
          left.push(array[i]);
      } else {
          right.push(array[i]);
      }
      
  }
  return quickSort(left).concat(pivot, quickSort(right));
}

快速排序改進求第K大值

思想是經過快排把數組切割成左中右三部分,將K與右邊數組(固然選左邊數組也能夠)長度做比較,若是右邊數組長度爲K-1,則中間元素即爲第K大值,若是右邊數組長度大於等於K,則第K大元素確定在右邊,則只須要對右邊數組遞歸求K大值,若是右邊數組長度小於K-1,則第K大值在左邊,在左數組求第k-1-right.length大值便可函數

function getK(array, k) {
  if(array.length <= 1){
      return array;
  }
  let middle = Math.floor(array.length / 2)
  let pivot = array.splice(middle, 1);
  let left =[], right = [];
  for(let i = 0; i < array.length; i++) {
      if(array[i] < pivot) {
          left.push(array[i]);
      } else {
          right.push(array[i]);
      }
      
  }
  if(right.length == k - 1){
      return pivot;
  } else if (right.length >= k) {
      return getK(right, k);
  } else {
      return getK(left, k-right.length-1);
  }
}

另外此方法也不是最佳解法,還有一種比較好的解法是利用創建K個元素的最小堆,新元素替換堆頂元素並調整堆,最後獲得的K個元素即爲最大的K個元素,時間複雜度NlogKpost

相關文章
相關標籤/搜索