Bootstrap

二叉树的遍历-递归法

前序遍历

思路

使用递归来实现遍历,构造一个deep函数来实现递归,递归需要确定好,入参和返回值,终止条件以及单层递归的逻辑
这里我们需要传入的入参是根节点,当根节点为null的时候递归结束
前序遍历:左右
中序遍历:左
后序遍历:左右
看中所在的位置,前序,中在前面,中序中在中间,后序中在后面
对于前序遍历,就要先存放中间节点,然后递归左子树,递归右子树

实现

// 前序遍历中左右
var preorderTraversal = function (root) {
  let result = [];

  const deep = function (root) {
    if (root === null) return;
    // 中
    result.push(root.val);
    // 左
    deep(root.left)
    // 右
    deep(root.right)
  }
  deep(root)
  return result;
}

中序遍历

思路

中序遍历就是把递归顺序改变,先遍历左子树,在存放中间节点,再遍历右子树

实现

// 中序遍历 左中右
var inorderTraversal = function (root) {
    const result = [];
    const deep = function(root){
        if(!root) return;
        // 左
        deep(root.left)
        // 中
        result.push(root.val);
        // 右
        deep(root.right)
    }
    deep(root)
    return result;
};

后序遍历

思路

后序遍历就是先遍历左子树,再遍历右子树,然后存放中间节点

实现

// 后序遍历 左右中
var postorderTraversal = function (root) {
    const result = [];
    const deep = function(root){
        if(!root) return;
        // 左
        deep(root.left)
        // 右
        deep(root.right)
        // 中
        result.push(root.val)
    }   
    deep(root);
    return result;
};
;