问答

关于js二叉树遍历的问题?

作者:admin 2021-05-09 我要评论

class TreeNode { constructor(val) { this.val = val; this.left = this.right = null; }}function init(){ var root = new TreeNode(5) var node1 = new TreeN...

在说正事之前,我要推荐一个福利:你还在原价购买阿里云、腾讯云、华为云服务器吗?那太亏啦!来这里,新购、升级、续费都打折,能够为您省60%的钱呢!2核4G企业级云服务器低至69元/年,点击进去看看吧>>>)
class TreeNode {
    constructor(val) {
        this.val = val;
        this.left = this.right = null;
    }
}

function init(){
    var root = new TreeNode(5)
    var node1 = new TreeNode(4)
    var node2 = new TreeNode(8)
    var node3 = new TreeNode(11)
    var node4 = new TreeNode(13)
    var node5 = new TreeNode(4)
    var node6 = new TreeNode(7)
    var node7 = new TreeNode(2)
    var node8 = new TreeNode(1)
    root.left = node1
    root.right = node2
    node1.left = node3
    node2.left = node4
    node2.right = node5
    node3.left = node6
    node3.right = node7
    node5.right = node8
    return root
}
var root = init()
init后得到这样一棵二叉树

image.png

如何遍历才能得到这样的数据?????

var result = [
    [5, 4, 11, 7],
    [5, 4, 11, 2],
    [5, 8, 13],
    [5, 8, 4, 1],
]

即按照分支左右分支遍历(描述可能有问题,大概是这个意思)

###

想象一下,在任何一个节点,你手里有这个节点和一条从根下来的路径。
接下来就是选择节点的下级路径中的每一条了,如果没有下级,则路径就是当前路径了。

function findPath (root) {
  const result = []
  if (!root) return result
  const list = [{ node: root, path: [root.val] }] // 从根开始遍历。list是待处理的节点和该节点路径
  while (list.length) {
    const { node, path } = list.shift()
    !node.left && !node.right && result.push(path)
    ;[node.left, node.right].filter(c => c && list.push({ node: c, path: [...path, c.val] }))
  }
  return result
}

以上是广度优先遍历。也可以深度优先:

function getPath (root) {
    if (!root) return []
    const left = getPath(root.left), right = getPath(root.right)
    const pathList = left.concat(right).map(p => (p.unshift(root.val), p))
    return pathList.length ? pathList : [[root.val]]
}
###

前序遍历+叶子节点判断

版权声明:本文转载自网络,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。本站转载出于传播更多优秀技术知识之目的,如有侵权请联系QQ/微信:153890879删除

相关文章
  • app内的web页面,img路径对,但是不显

    app内的web页面,img路径对,但是不显

  • 如何做下载功能?

    如何做下载功能?

  • 复杂正则表达式,实现思路

    复杂正则表达式,实现思路

  • vue一段简单的代码出现奇怪的问题?

    vue一段简单的代码出现奇怪的问题?

腾讯云代理商
海外云服务器