算法学习记录(十)

136 阅读1分钟

二叉树

问:

  1. 二叉树的先中后序遍历
  2. 非递归实现
  3. 宽度优先遍历,并求最大宽度

解:

  1. ①先序遍历(中左右);②中序遍历(左中右);③后序遍历(左右中)
    function ergodicTree(node) {
        if (!node) return
        // 此处获取node为先序遍历
        ergodicTree(node.left)
        // 此处获取node为中序遍历
        ergodicTree(node.right)
        // 此处获取node为后序遍历
    }

2.非递归

    // 先序遍历
    function preOrder(head) {
        const stack = [head]
        const res = []
        while (stack.length) {
            const node = stack.pop()
            res.push(node)
            if (node.right) stack.push(node.right)
            if (node.left) stack.push(node.left)
        }
        return res
    }
    // 后续遍历
    function postOrder(head) {
        const stack = [head]
        const res = []
        while (stack.length) {
            const node = stack.pop()
            res.push(node)
            if (node.left) stack.push(node.left)
            if (node.right) stack.push(node.right)
        }
        // [中 右 左]  逆序成   [左 右 中] 
        return res.reverse()
    }
    // 中序遍历
    function midOrder(head) {
        const stack = []
        const res = []
        let node = head
        while (node || stack.length) {
            while (node) {
                stack.push(node)
                node = node.left
            }
            const popNode = stack.pop()
            res.push(popNode.value)
            node = popNode.right
        }
        return res
    }

  1. 哈希表解法。每次出队列一个节点就记录这个节点所在层,并且给这个层的节点数加一
    function breadthOrder (head) {
        const queue = [head]
        const res = []
        head.floor = 1
        const maxFloor = {
            count: 0,
            floor: 0
        }
        const hashMap = new Map()
        while (queue.length) {
            const node = queue.shift()
            hashMap.has(node.floor) ? hashMap.set(node.floor, hashMap.get(node.floor) + 1) : hashMap.set(node.floor, 1)
            if (hashMap.get(node.floor) > maxFloor.count) {
                maxFloor.floor = node.floor
                maxFloor.count = hashMap.get(node.floor)
            }
            if (node.left) {
                node.left.floor = node.floor + 1
                queue.push(node.left)
            }
            if (node.right) {
                node.right.floor = node.floor + 1
                queue.push(node.right)
            }
            res.push(node.value)
        }
        return {
            arr: res,
            maxFloor
        }
    }