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 | 482 Views, 26166 Search Bots | 147 Words
| Browse | Archive
Tags: 每日算法题, 算法, 数据结构, 面试题, Daily Interview Problem, Data Structures and Algorithms, Computer Programming, Python, | English | Home Page | Category: Computing | 482 Views, 26166 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 | 482 Views, 26166 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 Problem] Witness of The Tall People
- Daily Interview Problem: Merge List Of Number Into Ranges
- Linode Support Ticket 10029540 - Other - Important Notice Regarding Ubuntu 17.10 Image
- Daily Interview Problem: Min Stack
- Making a Height Balanced Binary Search Tree
- [Daily Problem] Course Prerequisites
- Spreadsheet Column Title
- Algorithm Interview: Permutations of numbers
- Staying on a Chess Board
- ImageMagick Vulnerabilities - CVE-2016–3714
©2006~2024 SteakOverCooked - 0.01068 Seconds(s) - 2325.863 KB/s - 34 Online Memory: 499.06 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 !