JS-树:二叉树中序遍历


文章目录


前言

最近总结一下树的算法,研究树相关的知识。


一、中序遍历-递归

1、左中右

2、如下输入是:4 2 5 1 6 3 7

javascript 复制代码
  // 前序遍历
  const tree = {
    val: '1',
    left: {
      val: '2',
      left: { val: '4', left: null, right: null },
      right: { val: '5', left: null, right: null },
    },
    right: {
      val: '3',
      left: { val: '6', left: null, right: null },
      right: { val: '7', left: null, right: null },
    },
  }
	
  // 前序遍历
console.log(fun1(tree))

function fun1(root: any) {
  const arr: any[] = []
  const fun = (node: any) => {
    if (!node)
      return
    fun(node.left)
    arr.push(node.val)
    fun(node.right)
  }
  fun(root)
  return arr
}

二、中序遍历-队列

1、左中右

2、如下输入是:4 2 5 1 6 3 7

javascript 复制代码
function fun2(root: any) {
  const arr: any[] = []
  const stack = []
  let o = root
  while (stack.length || o) {
    while (o) {
      stack.push(o)
      o = o.left
    }
    const n = stack.pop()
    arr.push(n.val)
    o = n.right
  }
  return arr
}

总结

这就是树的二叉树中序遍历,希望能帮助到你!

相关推荐
Empty_77714 小时前
编程之python基础
开发语言·python
疯狂吧小飞牛15 小时前
Lua 中的 __index、__newindex、rawget 与 rawset 介绍
开发语言·junit·lua
寻星探路16 小时前
Java EE初阶启程记13---JUC(java.util.concurrent) 的常见类
java·开发语言·java-ee
哲Zheᗜe༘17 小时前
了解学习Python编程之python基础
开发语言·python·学习
落日漫游17 小时前
数据结构笔试核心考点
java·开发语言·算法
寻找华年的锦瑟18 小时前
Qt-配置文件(INI/JSON/XML)
开发语言·qt
HY小海18 小时前
【C++】AVL树实现
开发语言·数据结构·c++
workflower18 小时前
Fundamentals of Architectural Styles and patterns
开发语言·算法·django·bug·结对编程
Roc-xb18 小时前
ModuleNotFoundError: No module named ‘conda_token‘
开发语言·python·conda
人工干智能19 小时前
Python 开发中:`.ipynb`(Jupyter Notebook 文件)和 `.py`(Python 脚本文件)
开发语言·python·jupyter