To the Top
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 | 169 Views, 19599 Search Bots | 147 Words

Subscribe to Feed Burner | 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.


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
Tags: 每日算法题, 算法, 数据结构, 面试题, Daily Interview Problem, Data Structures and Algorithms, Computer Programming, Python, | English | Home Page | Cateogry: Computing | 169 Views, 19599 Search Bots | 147 Words Subscribe to Feed Burner

Related Articles

  1. Floor and Ceiling of a Binary Search Tree
  2. Algorithm Interview: Make the Largest Number
  3. Daily Interview Question: Edit Distance
  4. [Daily Problem] Angles of a Clock
  5. Daily Interview Question: Create a Simple Calculator
  6. Daily Interview Problem: Arithmetic Binary Tree
  7. Algorithm Interview: Lowest Common Ancestor of 2 Nodes in Binary Tree
  8. 56 Bytes
  9. Daily Interview Problem: Longest Substring With K Distinct Characters
  10. Plus One

Comments (0)

    Be the first one to comment this page !


Page Edited: October 30 2020 14:21:09 | RSS Subscription
How to Cook a Perfect Steak? | <meta name="robots" content="index, follow">