File tree Expand file tree Collapse file tree 1 file changed +92
-0
lines changed Expand file tree Collapse file tree 1 file changed +92
-0
lines changed Original file line number Diff line number Diff line change 1+ '''
2+ Given two nodes in a binary tree (with parent pointer available), find their lowest common ancestor.
3+
4+ Assumptions
5+
6+ There is parent pointer for the nodes in the binary tree
7+
8+ The given two nodes are not guaranteed to be in the binary tree
9+
10+ Examples
11+
12+ 5
13+
14+ / \
15+
16+ 9 12
17+
18+ / \ \
19+
20+ 2 3 14
21+
22+ The lowest common ancestor of 2 and 14 is 5
23+
24+ The lowest common ancestor of 2 and 9 is 9
25+
26+ The lowest common ancestor of 2 and 8 is null (8 is not in the tree)
27+
28+ '''
29+ class BinaryTree :
30+ def __init__ (self , val ):
31+ self .val = val
32+ self .left = None
33+ self .right = None
34+ self .parent = None
35+
36+
37+
38+ BTroot = BinaryTree (1 )
39+ BTrootl = BinaryTree (2 )
40+ BTrootr = BinaryTree (3 )
41+ BTrootll = BinaryTree (4 )
42+ BTrootlr = BinaryTree (5 )
43+ BTrootrl = BinaryTree (6 )
44+ BTrootrr = BinaryTree (7 )
45+ BTroot .left = BTrootl
46+ BTroot .right = BTrootr
47+ BTrootr .left = BTrootrl
48+ BTrootr .parent = BTroot
49+ BTrootl .parent = BTroot
50+ BTrootr .right = BTrootrr
51+ BTrootl .left = BTrootll
52+ BTrootl .right = BTrootlr
53+ BTrootrr .parent = BTrootr
54+ BTrootrl .parent = BTrootr
55+ BTrootlr .parent = BTrootl
56+ BTrootll .parent = BTrootl
57+
58+ def lca (root , p , q ):
59+ q = [root ]
60+ level = 0
61+ pLoc = (None , 0 )
62+ qLoc = (None , 0 )
63+ while q :
64+ curSize = len (q )
65+ for i in range (curSize ):
66+ curr = q .pop (0 )
67+ if curr == p :
68+ pLoc = (curr , level )
69+ elif curr == q :
70+ qLoc = (curr , level )
71+
72+ if curr .left :
73+ q .append (curr .left )
74+ if curr .right :
75+ q .append (curr .right )
76+ level += 1
77+
78+
79+
80+
81+
82+
83+
84+
85+
86+
87+
88+
89+
90+
91+
92+
You can’t perform that action at this time.
0 commit comments