JS实现二叉树
js没有树这个数据结构,使用object实现
const tree = {
value:'a',
left:{vlaue:'b',left:{},right:{}},
right:{vlaue:'b',left:{},right:{}}
}
对二叉树进行先序遍历
- 访问根节点
- 对左节点进行先序遍历
- 对右节点进行先序遍历
const preorder = (root)=>{
if(!root) return
console.log(root.value)
preorder(root.left)
preordre(root.right)
}
二叉树的中序遍历
- 对左节点进行中序遍历
- 访问根节点
- 对右节点进行中序遍历
const inorder = (root)=>{
if(!root) return
inorder(root.left)
console.log(root.value)
inorder(root.right)
}
二叉树的后序遍历
- 对左节点进行后序遍历
- 对右节点进行后序遍历
- 访问根节点
const postorder = (root)=>{
if(!root) return
postorder(root.left)
postorder(root.right)
console.log(root.value)
}