ID: 764

Write a function to find the highest common ancestor (not LCA) of two nodes in a binary tree.

Aligned LLM's Response:

Sure , I can help you with that ! Here ' s a Python function that finds the highest common ancest or ( H CA ) of two nodes in a binary tree : \n `` ` python \n def find _ h ca ( root , node 1 , node 2 ): \n if root is None : \n return None \n \n if root == node 1 or root == node 2 : \n return root \n \n left _ h ca = find _ h ca ( root . left , node 1 , node 2 ) \n right _ h ca = find _ h ca ( root . right , node 1 , node 2 ) \n \n if left _ h ca is not None and right _ h ca is not None : \n return root \n \n if left _ h ca is None and right _ h ca is not None : \n return right _ h ca \n \n if left _ h ca is not None and right _ h ca is None : \n return left _ h ca \n \n return None \n `` ` \n This function takes in the root of the binary tree , as well as the two nodes whose H CA we want to find . It recurs ively travers es the tree , comparing the two nodes to the current node . If either node is the current node , then that node is the H CA . If both nodes are children of the current node , then the current node is the H CA . If one node is a child of the current node and the other is not , then the non - child node is the H CA . If neither node is a child of the current node , then the function returns None . \n I hope this helps ! Let me know if you have any questions . </s>

Legend: Shifted positions  |  Marginal positions  |  Unshifted positions

Token Distributions

Previous
Home
Next