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 | 477 Views, 26096 Search Bots | 147 Words
| Browse | Archive
Tags: 每日算法题, 算法, 数据结构, 面试题, Daily Interview Problem, Data Structures and Algorithms, Computer Programming, Python, | English | Home Page | Category: Computing | 477 Views, 26096 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 | 477 Views, 26096 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
- New Vulnerabilities (CVE-2016-4581) have been detected in CentOS/RHEL/CloudLinux 7
- Daily Interview Problem: Merge Overlapping Intervals
- Absolute Path
- Windows Scripting
- First and Last Indices of an Element in a Sorted Array
- 56 Bytes
- Daily Interview Problem: Queue Using Two Stacks
- Daily Interview Problem: Merge List Of Number Into Ranges
- Daily Interview Problem: Deepest Node in a Binary Tree
- Longest Substring Without Repeating Characters
©2006~2024 SteakOverCooked - 0.00759 Seconds(s) - 2715.747 KB/s - 48 Online Memory: 494.65 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 !