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

Related Articles

  1. Print a tree level-by-level, with line-breaks
  2. [Daily Problem] Longest Increasing Subsequence
  3. Compare Version Numbers
  4. Sort a Partially Sorted List
  5. Consecutive Ones
  6. Daily Interview Question: Create a Simple Calculator
  7. Linode Support Ticket 10029540 - Other - Important Notice Regarding Ubuntu 17.10 Image
  8. Patterns for breaking down questions you haven
  9. [Daily Problem] Witness of The Tall People
  10. Algorithm Interview: Subarray With Target Sum

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="index, follow">