二叉树的前序遍历、中序遍历和后序遍历

题目要求

给你二叉树的根节点 root ,返回它节点值的 前序、中序、后序 遍历的结果。

思路分析

主要用递归的知识,思考,如果传递了一个节点过来我们需要做什么。
如果传递过来了一个节点,这个节点可能还包含有左子树右子树,什么时候是递归的终止条件
步骤:
1. 先判断传递过来的节点是否为空,为空则return,也就是递归退出条件
2. 将遍历的节点的值添加到外层变量数组中去,在js中也就是利用闭包的知识
3. 之后再对左子树和右子树做同样的操作
4. 返回闭包中的变量

代码实现

// 前序遍历
const preorderTraversal = function ( root ) {
    // 作为外层的存储容器
    const result = []
	// 递归函数
    const dfs = (root)=>{
	// 递归退出条件
        if(!root) return 
        result.push(root.val)
        dfs(root.left)
        dfs(root.right)
    }
    dfs(root)
    return result
}

// 中序遍历
const preorderTraversal = function ( root ) {
    // 作为外层的存储容器
    const result = []
	// 递归函数
    const dfs = (root)=>{
	// 递归退出条件
        if(!root) return
        dfs(root.left)
		result.push(root.val)
        dfs(root.right)
    }
    dfs(root)
    return result
}
// 后序遍历
const preorderTraversal = function ( root ) {
    // 作为外层的存储容器
    const result = []
	// 递归函数
    const dfs = (root)=>{
	// 递归退出条件
        if(!root) return
        dfs(root.left)
		dfs(root.right)
		result.push(root.val)
    }
    dfs(root)

迭代法遍历

//前序遍历:

// 入栈 右 -> 左
// 出栈 中 -> 左 -> 右
var preorderTraversal = function (root, res = []) {
  if (!root) return res
  const stack = [root]
  let cur = null
  while (stack.length) {
    cur = stack.pop()
    res.push(cur.val)
    cur.right && stack.push(cur.right)
    cur.left && stack.push(cur.left)
  }
  return res
}

//中序遍历:

// 入栈 左 -> 右
// 出栈 左 -> 中 -> 右

var inorderTraversal = function (root, res = []) {
  const stack = []
  let cur = root
  while (stack.length || cur) {
    if (cur) {
      stack.push(cur)
      // 左
      cur = cur.left
    } else {
      // --> 弹出 中
      cur = stack.pop()
      res.push(cur.val)
      // 右
      cur = cur.right
    }
  };
  return res
}

//后序遍历:

// 入栈 左 -> 右
// 出栈 中 -> 右 -> 左 结果翻转

var postorderTraversal = function (root, res = []) {
  if (!root) return res
  const stack = [root]
  let cur = null
  do {
    cur = stack.pop()
    res.push(cur.val)
    cur.left && stack.push(cur.left)
    cur.right && stack.push(cur.right)
  } while (stack.length)
  return res.reverse()
}
posted @ 2023-01-01 21:55  含若飞  阅读(22)  评论(0编辑  收藏  举报