lynhao / day-by-day

每日更新一道算法题
MIT License
0 stars 0 forks source link

实现一个对称二叉树 #16

Open lynhao opened 4 years ago

lynhao commented 4 years ago

题目: 实现一个对称二叉树, 并判断当前数组是否符合规范

eg1: arr = [1,2,2,3,4,4,3] output: true

eg2: arr = [1,3,4] output: false

lynhao commented 4 years ago
class Node {
    constructor(val) {
        this.val = val
        this.left = undefined
        this.right = undefined
    }
}

class Tree {
    constructor(arr) {
        let nodelist = []
        for (let i = 0, len = arr.length; i < len; i++) {
            let node = new Node(arr[i])
            nodelist.push(node)
            if (i > 0) {
                // 获取层
                let layer = Math.floor(Math.sqrt(i + 1))
                // 获取当前层的起始位置
                let index = Math.pow(2, layer) - 1
                // 获取上一层的起始位置
                let parentIndex = Math.pow(2, layer - 1) -1
                // 获取当前节点的父节点
                let parent = nodelist[parentIndex + Math.floor((i - index) / 2)]
                if (parent.left) {
                    parent.right = node
                } else {
                    parent.left = node
                }
            }
        }
        let root = nodelist.shift()
        nodelist.length = 0
        return root
    }
    static symmetry(root) {
        if (!root) return true;
        let walk = (left, right) => {
            if (!left && !right) return true;
            if (!left && right || left && !right || left.val !== right.val) {
                return false
            }
            return walk(left.left, right.right) && walk(left.right, right.left)
        }
        return walk(root.left, root.right)
    }
}

var root = new Tree([1,2,2,3,4,4,3])
Tree.symmetry(root)  // true

var root = new Tree([1,2,3])
Tree.symmetry(root)  // false