JS-树:二叉树前序遍历(先序遍历)



前言

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


一、前序遍历-递归

1、从根出发,然后左边然后右边
2、如下输入是:a b d e c f g

  // 前序遍历
  const tree = {
    
    
    val: 'a',
    left: {
    
    
      val: 'b',
      left: {
    
     val: 'd', left: null, right: null },
      right: {
    
     val: 'e', left: null, right: null },
    },
    right: {
    
    
      val: 'c',
      left: {
    
     val: 'f', left: null, right: null },
      right: {
    
     val: 'g', left: null, right: null },
    },
  }
	
  // 前序遍历
console.log(fun1(tree))

function fun1(root: any) {
    
    
  const arr: any[] = []

  const fun = (node: any) => {
    
    
    if (node) {
    
    
      arr.push(node.val)
      fun(node.left)
      fun(node.right)
    }
  }

  fun(root)

  return arr
}

二、前序遍历-队列

1、从根出发,然后左边然后右边
2、如下输入是:a b d e c f g

function fun2(root: any) {
    
    
  const arr: any[] = []
  const stack = [root]
  while (stack.length > 0) {
    
    
    const o = stack.pop()
    arr.push(o.val)
    o.right && stack.push(o.right)
    o.left && stack.push(o.left)
  }
  return arr
}

总结

这就是树的二叉树前序遍历(先序遍历),希望能帮助到你!

猜你喜欢

转载自blog.csdn.net/smileKH/article/details/133708354
今日推荐