Leetcode236. Lowest Common Ancestor of a Binary Tree

Leetcode236. Lowest Common Ancestor of a Binary Tree

Given a binary tree, find the lowest common ancestor (LCA) of two given nodes in the tree.
According to the definition of LCA on Wikipedia: “The lowest common ancestor is defined between two nodes p and q as the lowest node in T that has both p and q as descendants (where we allow a node to be a descendant of itself).”
Given the following binary tree: root = [3,5,1,6,2,0,8,null,null,7,4]
Here Insert Picture Description

Example 1:

Input: root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 1
Output: 3
Explanation: The LCA of nodes 5 and 1 is 3.

Example 2:

Input: root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 4
Output: 5
Explanation: The LCA of nodes 5 and 4 is 5, since a node can be a descendant of itself according to the LCA definition.

Note:

  • All of the nodes’ values will be unique.
  • p and q are different and both values will exist in the binary tree.

Thinking

  • Two nodes p, q are two cases: p and q are the same subtree, p and q in different sub-trees

  • From the root node traversal, recursive query node tree information about the child

    • Recursive termination condition: If the current node is empty or equal to por q, the current node returns.
    • Recursively traverse left and right subtrees, if found around sub-tree nodes are not empty, it means that pand qare in the left and right subtrees, and therefore, the current node is the most recent common ancestor;
    • If one of the left and right subtrees is not empty, the node returns a non-null.
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
    if(root == null || root == p || root == q)  return root;
    TreeNode left = lowestCommonAncestor(root.left, p, q);
    TreeNode right = lowestCommonAncestor(root.right, p, q);
    if(left && right)   return root;
    return left ? left : right;
}
def lowestCommonAncestor(self, root, p, q):
        """
        :type root: TreeNode
        :type p: TreeNode
        :type q: TreeNode
        :rtype: TreeNode
        """
		# If looking for me, return myself
        if root == p or root == q:
            return root
        
        left = right = None
        # else look in left and right child
        if root.left:
            left = self.lowestCommonAncestor(root.left, p, q)
        if root.right:
            right = self.lowestCommonAncestor(root.right, p, q)

        # if both children returned a node, means
        # both p and q found so parent is LCA
        if left and right:
            return root
        else:
        # either one of the chidren returned a node, meaning either p or q found on left or right branch.
        # Example: assuming 'p' found in left child, right child returned 'None'. This means 'q' is
        # somewhere below node where 'p' was found we dont need to search all the way, 
        # because in such scenarios, node where 'p' found is LCA
            return left or right

DFS

Simply use DFS to search for p and q, and record their paths once hit, then just compare the two paths and you will find the lowest common ancestor!

class Solution:
    def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
        stack, p_trace, q_trace = [], [], []
		
        while True:
            if root.left:
                stack.append(root)
                root.left, root = None, root.left
            elif root.right:
                stack.append(root)
                root.right, root = None, root.right
            else:
                if root is p:
                    p_trace = stack[:]
                    p_trace.append(root)
                if root is q:
                    q_trace = stack[:]
                    q_trace.append(root)
                if p_trace and q_trace:
                    break
                root = stack.pop()
				
        i, m = 0, min(len(p_trace), len(q_trace))
        while i < m and p_trace[i] is q_trace[i]:
            ans = p_trace[i]
            i += 1
        return ans
Published 89 original articles · won praise 8 · views 5776

Guess you like

Origin blog.csdn.net/magic_jiayu/article/details/104400430