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, 26163 Search Bots | 147 Words
| Browse | Archive
Tags: 每日算法题, 算法, 数据结构, 面试题, Daily Interview Problem, Data Structures and Algorithms, Computer Programming, Python, | English | Home Page | Category: Computing | 482 Views, 26163 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, 26163 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
- Find Pythagorean Triplets
- Plus One
- ImageMagick Vulnerabilities - CVE-2016–3714
- Design Tic-Tac-Toe
- Daily Interview Problem: Look and Say Sequence
- Daily Interview Problem: Largest BST in a Binary Tree
- Daily Interview Problem:Create a balanced binary search tree
- Algorithm Interview: Convert Roman Numerals to Decimal
- Patterns for breaking down questions you haven
- Daily Interview Problem: Spiral Traversal of Grid
©2006~2024 SteakOverCooked - 0.00786 Seconds(s) - 2435.755 KB/s - 32 Online Memory: 493.17 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" />
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 !