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 | 502 Views, 27442 Search Bots | 147 Words
| Browse | Archive
Tags: 每日算法题, 算法, 数据结构, 面试题, Daily Interview Problem, Data Structures and Algorithms, Computer Programming, Python, | English | Home Page | Category: Computing | 502 Views, 27442 Search Bots | 147 Words
| Browse | Archive
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 | 502 Views, 27442 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
Related Articles
- Daily Interview Question: Word Search
- Daily Interview Problem: Merge Overlapping Intervals
- PHP Unit Tests on VPS Server
- A trick for getting good at coding interviews FASTER
- Daily Interview Problem: Longest Substring With K Distinct Characters
- New Vulnerabilities (CVE-2016-4581) have been detected in CentOS/RHEL/CloudLinux 7
- Daily Interview Problem: Find the k-th Largest Element in a List
- [Daily Problem] Witness of The Tall People
- [Daily Problem] Course Prerequisites
- Daily Interview Problem: Maximum Profit From Stocks
©2006~2024 SteakOverCooked - 0.0068 Seconds(s) - 3023.767 KB/s - 17 Online Memory: 495.41 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="index, follow">
18:54:01 up 13 days, 18:33, 2 users, load average: 0.98, 0.86, 0.73 - Server PHP Version: 7.4.33
Comments (0)
Read & Write - Normal - Mini - Post - All Comments - Statistics
Be the first one to comment this page !