输出二叉树的右视图

题目要求

image

题目链接

思路分析

方法一:刚开始做的时候没有什么思路,就采用了最笨的方法

  • 根据中序和先序求出二叉树
  • 得到层序遍历的结果
  • 得到每一层的最后一个元素
    方法比较笨拙,但是也回顾了之前所学的一些东西,感兴趣的可以试试。
    方法二:

代码参考

const solve = function (xianxu, zhongxu) {
  // 根据前序和中序获得二叉树
  const reductionRoot = function (pre, vin) {
    if (!pre.length || !vin.length) return null
    const root = new TreeNode(pre.shif())
    const index = vin.indexOf(root.val)
    root.left = reductionRoot(pre, vin.slice(0, index))
    root.right = reductionRoot(pre, vin.slice(index + 1))
    return root
  }
  // 层序遍历
  const sequenceTranversal = function (root) {
    const result = [], tempQueue = []
    if (!root) return result
    tempQueue.push(root)
    while (!tempQueue.length) {
      const len = tempQueue.length
      const curLevel = []
      for (let i = 0; i < len; i++) {
        const node = tempQueue.shift()
        curLevel.push(node.val)
        node.left && tempQueue.push(node.left)
        node.right && tempQueue.push(node.right)
      }
      result.push(curLevel)
    }
    return result
  }
  // 每一层的最后一个值
  const getLast = function (arr) {
    const res = []
    for (let i = 0; i < arr.length; i++) {
      res.push(result[i].slice(-1)[0])
    }
    return res
  }
}
posted @ 2023-01-11 13:06  含若飞  阅读(27)  评论(0编辑  收藏  举报