236. Lowest Common Ancestor of a Binary Tree

# Medium

Two methods:

  1. Harder to implement, but easy to understand. Every node returns information of <ancestor, numOf(p,q)>, which means:

    1. if in this node's tree, don't find (p, q), then return <NULL, 0>.

    2. if find one of (p, q), then return <NULL, 1>.

    3. if find both of (p, q), then return <root, 2>. ⚠️this node may be p or q, count it as well.

  2. Easy to implement, but harder to understand. From top to bottom, very recursive return:

    1. if only node.left or node.right contains (p, q), continue returning the returnValue of lower level.

    2. if both of node.left and node.right contian p and q, they must be separated in left and right subtree, then return node, this is the real ancestor.

    3. for higher level recursive, this node will continue passing up, because only one of any its parents' child has no-NULL returnValue.

Solution 1:

  1. edge case in main function.

  2. traversal each node from bottom to up, to pass <ancestor, numOf(p, q)>.

  3. return ancestor in main function.

Same logic is applied to two cases

Time complexity = O(n)O(n) , 因为每个节点只访问一次。space complexity = O(h)O(h) ,这里的空间复杂度指的是栈深,最坏的情况就是所有点在一条直线上. nn is the number of nodes.

Same logic is applied to two cases

Time complexity = O(n)O(n) , 因为每个节点只访问一次。space complexity = O(h)O(h) ,这里的空间复杂度指的是栈深,最坏的情况就是所有点在一条直线上. nn is the number of nodes.

Last updated

Was this helpful?