【leetcode】993.二叉树的堂兄弟节点

33 阅读1分钟

leetcode-993.png

这种需要用BFS或者DFS来解决了

BFS

记录好父节点就行,因为每次层次遍历都是在同一层

var isCousins = function (root, x, y) {
    let queue = []
    queue.push(root)
    while (queue.length) {
        let size = queue.length
        let xRoot = null, yRoot = null
        for (let i = 0; i < size; ++i) {
            let node = queue.shift()
            if (node.left) {
                if (node.left.val === x) {
                    xRoot = node
                }
                if (node.left.val === y) {
                    yRoot = node
                }
                queue.push(node.left)
            }
            if (node.right) {
                if (node.right.val === x) {
                    xRoot = node
                }
                if (node.right.val === y) {
                    yRoot = node
                }
                queue.push(node.right)
            }
        }
        if (xRoot && yRoot && xRoot !== yRoot) {
            return true
        }
    }
    return false
};

DFS

对于DFS需要记录下层次深度了

因为不知道找到符合条件的节点的深度,找到后记录深度以及父节点然后判断就行了

var isCousins = function (root, x, y) {
    let xParent = null, yParent = null
    let xDepth = -1, yDepth = -1
    var dfs = function (node, parent, depth) {
        if (!node) {
            return
        }
        if (node.val === x) {
            xParent = parent
            xDepth = depth
        }
        if (node.val === y) {
            yParent = parent
            yDepth = depth
        }
        dfs(node.left, node, depth + 1)
        dfs(node.right, node, depth + 1)
    }
    dfs(root, null, 0)
    return xDepth === yDepth ? xParent !== yParent : false
};