To the Top
File:  root - text - article - 2019 - 12 - largest-bst-in-a-binary-tree.txt.txt
Tags: 每日算法题, 算法, 数据结构, 面试题, Daily Interview Problem, Data Structures and Algorithms, Computer Programming, Python, | English | Home Page | Category: Computing | 243 Views, 19826 Search Bots | 118 Words

Subscribe to Feed Burner | Browse | Archive
Hi, here's your problem today. This problem was recently asked by Twitter:

You are given the root of a binary tree. Find and return the largest subtree of that tree, which is a valid binary search tree.

Here's a starting point:


class TreeNode:
def __init__(self, key):
self.left = None
self.right = None
self.key = key

def __str__(self):
# preorder traversal
answer = str(self.key)
if self.left:
answer += str(self.left)
if self.right:
answer += str(self.right)
return answer

def largest_bst_subtree(root):
# Fill this in.

# 5
# / \
# 6 7
# / / \
# 2 4 9
node = TreeNode(5)
node.left = TreeNode(6)
node.right = TreeNode(7)
node.left.left = TreeNode(2)
node.right.left = TreeNode(4)
node.right.right = TreeNode(9)
print largest_bst_subtree(node)
#749
Tags: 每日算法题, 算法, 数据结构, 面试题, Daily Interview Problem, Data Structures and Algorithms, Computer Programming, Python, | English | Home Page | Cateogry: Computing | 243 Views, 19826 Search Bots | 118 Words Subscribe to Feed Burner

Related Articles

  1. Daily Interview Problem: Given two arrays, write a function to compute their intersection.
  2. Daily Interview Problem: Contiguous Subarray with Maximum Sum
  3. Daily Interview Problem: Buddy Strings
  4. Longest Substring Without Repeating Characters
  5. Skip the readings, focus on problems. And use all the hints!
  6. Autorun.inf Virus Protection
  7. Find Missing Numbers in an Array
  8. Daily Interview Problem: Validate Binary Search Tree
  9. Batch Programming in XP
  10. Floor and Ceiling of a Binary Search Tree

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" />