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

Related Articles

  1. Maximum In A Stack
  2. Daily Interview Problem: Merge List Of Number Into Ranges
  3. YES!!
  4. Compare Version Numbers
  5. 56 Bytes
  6. Daily Interview Problem: Decode String
  7. [Daily Problem] Remove k-th Last Element From Linked List
  8. Algorithm Interview: Shifted String
  9. Invert a Binary Tree
  10. Design Tic-Tac-Toe

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