JS二叉树前序遍历中序遍历后序遍历

我又来了,这次为大家带来关于二叉树的内容

首先,先来一个简单的二叉树
图有点抽象,大家尽量看,哈哈
在这里插入图片描述

这次讲的是二叉树的遍历

分为:前序遍历、中序遍历、后序遍历

一、前序遍历

先根次序遍历

先打印当前,再打印左边,再打印右边

如上图所示,遍历打印顺序:ABCDEFG

上代码:

function Node(value) {
    this.value = value
    this.left = null
    this.right = null
}
let a = new Node('A')
let b = new Node('B')
let c = new Node('C')
let d = new Node('D')
let e = new Node('E')
let f = new Node('F')
let g = new Node('G')

a.left = b
a.right = c
b.left = d
b.right = e
c.left = f
c.right = g

function bianli(root) {
    if (root === null) return
    console.log(root.value)
    bianli(root.left)
    bianli(root.right)
}
bianli(a)

在这里插入图片描述

二、中序遍历

中根次序遍历

先打印左边,再打印当前,再打印右边

遍历顺序:DBEAFCG

function Node(value) {
    this.value = value
    this.left = null
    this.right = null
}
let a = new Node('A')
let b = new Node('B')
let c = new Node('C')
let d = new Node('D')
let e = new Node('E')
let f = new Node('F')
let g = new Node('G')

a.left = b
a.right = c
b.left = d
b.right = e
c.left = f
c.right = g

function bianli(root) {
    if (root === null) return
    bianli(root.left)
    console.log(root.value)
    bianli(root.right)
}
bianli(a)

在这里插入图片描述

三、后序遍历

后根次序遍历

先打印左边,再打印右边,再打印当前

遍历顺序:DEBFGCA

function Node(value) {
    this.value = value
    this.left = null
    this.right = null
}
let a = new Node('A')
let b = new Node('B')
let c = new Node('C')
let d = new Node('D')
let e = new Node('E')
let f = new Node('F')
let g = new Node('G')

a.left = b
a.right = c
b.left = d
b.right = e
c.left = f
c.right = g

function bianli(root) {
    if (root === null) return
    bianli(root.left)
    bianli(root.right)
    console.log(root.value)
}
bianli(a)

在这里插入图片描述

学无止境,加油!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值