算法基礎之二叉樹

本文主要包括樹相關的算法,二叉樹結點基本結構如下

function TreeNode(x) {
  this.val = x;
  this.left = null;
  this.right = null;
}

本文還會繼續(xù)更新。

二叉樹的深度

function depth(pRoot){
    if(!pRoot){
        return 0;
    }

    var depth = 0;
    var currDepth = 0;
    dfs(pRoot);
    return depth;

    function dfs(node){
        if(!node){
            depth = depth > currDepth ? depth : currDepth;
            return;
        }
        currDepth++;
        dfs(node.left);
        dfs(node.right);
        currDepth--;
    }
}

二叉樹的前序遍歷

function preOrder(root){
  if(!root)
    return [];
  var result = [];
  _preOrder(root);
  return result;

  function _preOrder(node){
    result.push(node.val);
    node.left && _preOrder(node.left);
    node.right && _preOrder(node.right);
  }
}

二叉樹的中序遍歷

function inOrder(root){
  if(!root)
    return [];
  var result = [];
  _inOrder(root);
  return result;

  function _inOrder(node){
    node.left && _inOrder(node.left);
    result.push(node.val);
    node.right && _inOrder(node.right);
  }
}

二叉樹的后序遍歷

function postOrder(root){
  if(!root)
    return [];
  var result = [];
  _postOrder(root);
  return result;

  function _postOrder(node){
    node.left && _postOrder(node.left);
    node.right && _postOrder(node.right);
    result.push(node.val);
  }
}

二叉樹的層序遍歷

/* function TreeNode(x) {
    this.val = x;
    this.left = null;
    this.right = null;
} */
function printFromTopToBottom(root){
    if (!root) {
        return [];
    }
    var queue = [];
    queue.push(root);
    var result = [];

    while (queue.length) {
        var temp = queue.shift();
        result.push(temp.val);
        if (temp.left) {
            queue.push(temp.left);
        }
        if (temp.right) {
            queue.push(temp.right);
        }
    }
    return result;
}

根據層序遍歷建立二叉樹

//層序的空節(jié)點使用 null
function Tree(arr, node, num){   //也可以通過 new 調用
  if(!arr || arr.length === 0){
      return new TreeNode(null);
  }
  num = num || 1;
  node = node || new TreeNode(arr[num - 1]);

  var curr = node;
  if(num * 2 - 1 < arr.length && arr[num * 2 - 1] != null){
    curr.left = new TreeNode(arr[num * 2 - 1]);
    Tree(arr, curr.left, num * 2);
  }
  if(num * 2 < arr.length && arr[num * 2] != null){
    curr.right = new TreeNode(arr[num * 2]);
    Tree(arr, curr.right, num * 2 + 1);
  }
  return node;
}

根據中序遍歷和前序遍歷重建二叉樹

function reBuildTree_pi(pre, vin){
    if(pre.length == 0 || vin.length == 0 || pre.length !== vin.length){
        return null;
    };
    var index = vin.indexOf(pre[0]);
    var left = vin.slice(0,index);
    var right = vin.slice(index+1);
    var node = new TreeNode(vin[index]);
    node.left = reBuildTree_pi(pre.slice(1,index+1),left);
    node.right = reBuildTree_pi(pre.slice(index+1),right);
    return node;
}

根據中序遍歷和后序遍歷重建二叉樹

function reBuildTree_ip(vin, post){
    if(post.length == 0 || vin.length == 0 || vin.length !== post.length){
        return null;
    };
    var index = vin.indexOf(post.pop());
    var left = vin.slice(0,index);
    var right = vin.slice(index+1);
    var node = new TreeNode(vin[index]);
    node.left = reBuildTree_ip(left, post.slice(0,index));
    node.right = reBuildTree_ip(right, post.slice(index));
    return node;
}

求二叉樹的最遠節(jié)點距離

function maxDistance(root){     //root 二叉樹根節(jié)點;
  if(root === null) return 0;
  var max = 0;
  _maxDistance(root, max);
  return max;    //函數返回最大值

  function _maxDistance(curr){   //curr: 當前節(jié)點;max: 最大值;
    if(curr === null) return 0;
    var leftDepth = curr.left ? _maxDistance(curr.left) : 0;
    var rightDepth = curr.right ? _maxDistance(curr.right) : 0;
    if(leftDepth + rightDepth > max) max = leftDepth + rightDepth;
    return leftDepth > rightDepth ? leftDepth + 1 : rightDepth + 1;
  }
}

二叉樹的鏡像

function mirror(root){
    if(!root){
        return null;
    }
    var temp = root.left;
    root.left = root.right;
    root.right = temp;
    if(root.left){
        Mirror(root.left);
    }
    if(root.right){
        Mirror(root.right);
    }
}

二叉搜索樹轉雙向鏈表

將左子樹構成雙向鏈表,返回的是左子樹的尾結點,將其連接到root的左邊;
將右子樹構成雙向鏈表,將其追加到root結點之后,并返回尾結點;
向左遍歷返回的鏈表至頭結點處,即為所求雙向鏈表的首結點。

function convert(pRootOfTree){
    if(!pRootOfTree) {
        return null;
    }
    var lastNode = null;
    lastNode = ConvertNode(pRootOfTree);
    var head = lastNode;
    while(head && head.left) {
        head = head.left;
    }
    return head;

    function ConvertNode(node){
        if(!node){
            return;
        }
        if(node.left) {
            lastNode = ConvertNode(node.left);
        }
        node.left = lastNode;
        if(lastNode){
            lastNode.right = node;
        }
        lastNode = node;
        if(node.right){
            lastNode = ConvertNode(node.right);
        }
        return lastNode;
    }
}

判斷是否平衡二叉樹

function isBalancedTree(pRoot){
    if(!pRoot){
        return true;
    }

    var left = TreeDepth(pRoot.left);
    var right = TreeDepth(pRoot.right);
    var diff = left - right;

    if(diff > 1 || diff < -1)
        return false;

    return IsBalanced_Solution(pRoot.left) && IsBalanced_Solution(pRoot.right);

    function TreeDepth(pRoot){
        if(!pRoot){
            return 0;
        }

        var depth = 0;
        var currDepth = 0;
        dfs(pRoot);
        return depth;

        function dfs(node){
            if(!node){
                depth = depth > currDepth ? depth : currDepth;
                return;
            }
            currDepth++;
            dfs(node.left);
            dfs(node.right);
            currDepth--;
        }
    }
}

判斷是否對稱二叉樹

function isSymmetrical(pRoot){
    if(!pRoot){
      return true;
    }
    return symmetrical(pRoot, pRoot);

    function symmetrical(node1,node2){
        if(!node1 && !node2)
            return true;
        if(!node1 || !node2)
            return false;
        if(node1.val != node2.val)
            return false;
        return symmetrical(node1.left, node2.right) && symmetrical(node1.right, node2.left);
    }
}

判斷是否完全二叉樹

function isPrefectTree(root){
  if(!root)
    return true;
  var que = [];
  que.push(root);
  var curr;
  while(curr = que.shift()){
    que.push(curr.left);
    que.push(curr.right);
  }
  while (que.length > 0){
    if (que.pop())
      return false;
  }
  return true;
}

判斷是否滿二叉樹

function isFullTree(root){
  if(!root)
    return true;
  var que = [];
  que.push(root);
  var curr;
  var nodeNum = 0;

  while(curr = que.shift()){
    que.push(curr.left);
    que.push(curr.right);
    nodeNum++;
  }
  while (que.length > 0){
    if (que.pop())
      return false;
  }

  return (nodeNum & (nodeNum + 1)) === 0;
}
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內容

  • 數據結構和算法--二叉樹的實現(xiàn) 幾種二叉樹 1、二叉樹 和普通的樹相比,二叉樹有如下特點: 每個結點最多只有兩棵子...
    sunhaiyu閱讀 6,710評論 0 14
  • B樹的定義 一棵m階的B樹滿足下列條件: 樹中每個結點至多有m個孩子。 除根結點和葉子結點外,其它每個結點至少有m...
    文檔隨手記閱讀 13,703評論 0 25
  • 第一章 緒論 什么是數據結構? 數據結構的定義:數據結構是相互之間存在一種或多種特定關系的數據元素的集合。 第二章...
    SeanCheney閱讀 6,013評論 0 19
  • 1.樹(Tree): 樹是 n(n>=0) 個結點的有限集。當 n=0 時稱為空樹。在任意一顆非空樹中:有且僅有一...
    ql2012jz閱讀 1,204評論 0 3
  • 這幾天開學,學校還在上課,最近也是在找工作,很多天都沒有更新文章,現(xiàn)在補一篇二叉樹的文章。 最近校招公司的筆試陸續(xù)...
    zero_sr閱讀 4,119評論 0 5

友情鏈接更多精彩內容