1. 程式人生 > 其它 >二叉樹的遍歷與構建

二叉樹的遍歷與構建

二叉樹的四種遍歷方式:
二叉樹的遍歷,即按照某種次序依次訪問二叉樹中所有的結點,使得每個結點被依照次序進行訪問且僅被訪問一次。
四種遍歷方式分別為:
深度優先:先序遍歷、中序遍歷、後序遍歷
廣度優先:層序遍歷

  • 以中序遍歷為例:

中序遍歷的遞迴實現

const inorderTraversal = (root) => {
    const res = [];
    const inorder = (root) => {
        if (root == null) {
            return;
        }
        inorder(root.left); // 先遞迴左子樹
        res.push(root.val); // 將當前節點值推入res
        inorder(root.right); // 再遞迴右子樹
    };
    inorder(root);
    return res;
};

中序遍歷的迭代實現

const inorderTraversal = (root) => {
  const res = [];
  const stack = [];

  while (root) {        // 能壓棧的左子節點都壓進來
    stack.push(root);
    root = root.left;
  }
  while (stack.length) {
    let node = stack.pop(); // 棧頂的節點出棧
    res.push(node.val);     // 在壓入右子樹之前,處理它的數值部分(因為中序遍歷)
    node = node.right;      // 獲取它的右子樹
    while (node) {          // 右子樹存在,執行while迴圈    
      stack.push(node);     // 壓入當前root
      node = node.left;     // 不斷壓入左子節點
    }
  }
  return res;
};

能夠對二叉樹進行遍歷,同時也能依據遍歷結果對二叉樹進行重建

由前序遍歷和中序遍歷構建二叉樹

let buildTree = (preorder, inorder) => {

  //當preorder和inorder均為空的時候說明已經到了空節點
  if (!preorder.length || !inorder.length) return null;

  //建立根節點 -> preorder[0]
  let node = new TreeNode(preorder[0]);

  //找到preoder[0]對應inorder中的位置
  let index = inorder.indexOf(preorder.shift());

  //左右子樹遞迴
  node.left = buildTree(preorder, inorder.slice(0, index));
  node.right = buildTree(preorder, inorder.slice(index + 1));

  //返回根節點
  return node;
};

本文來自部落格園,作者:starking_front-end,轉載請註明原文連結:https://www.cnblogs.com/starking-985/p/15966128.html