Lowest Common Ancestor of a Binary Tree Leetcode 236 in Python 3
Given a binary tree, find the lowest common ancestor (LCA) of two given nodes in the tree. 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).
Approach - Here we will simple keep a track of parent of each node through an array. When we reach node P and Q we put its parent in a Hash Map or dictionary which we will use later to find their common ancestors.The code is self explanatory. Just try yourself before peeking into code.
|
|