File: root - text - article - 2020 - 01 - lowest-common-ancestor-of-2-nodes-in-binary-tree.txt
Tags: 每日算法题, 算法, 数据结构, 面试题, Daily Interview Problem, Data Structures and Algorithms, Computer Programming, Python, | English | Home Page | Category: Computing | 222 Views, 21966 Search Bots | 147 Words
| Browse | Archive
![Subscribe to Feed Burner Subscribe to Feed Burner](/images/form/rss.gif)
Tags: 每日算法题, 算法, 数据结构, 面试题, Daily Interview Problem, Data Structures and Algorithms, Computer Programming, Python, | English | Home Page | Category: Computing | 222 Views, 21966 Search Bots | 147 Words
![Subscribe to Feed Burner Subscribe to Feed Burner](/images/form/rss.gif)
Hi, here's your problem today. This problem was recently asked by Apple:
You are given the root of a binary tree, along with two nodes, A and B. Find and return the lowest common ancestor of A and B. For this problem, you can assume that each node also has a pointer to its parent, along with its left and right child.
Tags: 每日算法题, 算法, 数据结构, 面试题, Daily Interview Problem, Data Structures and Algorithms, Computer Programming, Python, | English | Home Page | Cateogry: Computing | 222 Views, 21966 Search Bots | 147 Words You are given the root of a binary tree, along with two nodes, A and B. Find and return the lowest common ancestor of A and B. For this problem, you can assume that each node also has a pointer to its parent, along with its left and right child.
class TreeNode:
def __init__(self, val):
self.left = None
self.right = None
self.parent = None
self.val = val
def lowestCommonAncestor(root, a, b):
# Fill this in.
# a
# / \
# b c
# / \
# d* e*
root = TreeNode('a')
root.left = TreeNode('b')
root.left.parent = root
root.right = TreeNode('c')
root.right.parent = root
a = root.right.left = TreeNode('d')
root.right.left.parent = root.right
b = root.right.right = TreeNode('e')
root.right.right.parent = root.right
print lowestCommonAncestor(root, a, b).val
# c
![Subscribe to Feed Burner Subscribe to Feed Burner](/images/form/rss.gif)
Related Articles
- Daily Interview Problem: Tree Serialization
- Autorun.inf Virus Protection
- Daily Interview Problem: Reconstrunct Binary Tree from Preorder and Inorder Traversals
- Daily Interview Problem: Group Words that are Anagrams
- Invert a Binary Tree
- [Daily Problem] Add two numbers as a linked list
- Algorithm Interview: Subarray With Target Sum
- Windows Scripting
- Absolute Path
- Delphi Dynamic Array
©2006~2024 SteakOverCooked - 0.01348 Seconds(s) - 1454.954 KB/s - 31 Online
Memory: 495.1 KB
18:54:01 up 13 days, 18:33, 2 users, load average: 0.98, 0.86, 0.73 - Server PHP Version: 7.4.33
How to Cook a Perfect Steak? | <meta name="robots" content="noindex, follow" />
![](/images/top.jpg)
18:54:01 up 13 days, 18:33, 2 users, load average: 0.98, 0.86, 0.73 - Server PHP Version: 7.4.33
Read & Write - Normal - Mini - Post - All Comments - Statistics
Be the first one to comment this page !