harrytothemoon / leetcodeAplus

Leetcode meeting note
2 stars 0 forks source link

[865] Smallest Subtree with all the Deepest Nodes #66

Open tsungtingdu opened 3 years ago

tsungtingdu commented 3 years ago
var subtreeWithAllDeepest = function(root) {
    return traverse(root).node

    function traverse(node) {
        if (!node) return { node: null, level: 0 }

        let left = traverse(node.left)
        let right = traverse(node.right)

        if (left.level > right.level) return { node: left.node, level: left.level + 1 }
        if (right.level > left.level) return { node: right.node, level: right.level + 1 }

        return { node: node, level: left.level + 1}
    }
};