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 | 170 Views, 20024 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 | 170 Views, 20024 Search Bots | 147 Words Subscribe to Feed Burner

Related Articles

  1. Spectrum Master
  2. Daily Interview Question: Create a Simple Calculator
  3. Daily Interview Puzzle: Intersection of Linked Lists
  4. Daily Interview Problem: 3 Sum
  5. Skip the readings, focus on problems. And use all the hints!
  6. Daily Interview Question: Edit Distance
  7. Two-Sum
  8. Daily Interview Problem: Room scheduling
  9. [Daily Problem] Longest Palindromic Substring
  10. ImageMagick Vulnerabilities -  CVE-2016–3714

Comments (0)

    Be the first one to comment this page !


Page Edited: May 11 2024 14:36:49 | RSS Subscription
How to Cook a Perfect Steak? | <meta name="robots" content="noindex, follow" />