打卡|Twitter|Largest BST in a Binary Tree
Google|Sorting A List with 3 Unique Numbers
Airbnb|First and Last Indices of an Element in a Sorted Array
Google|Create a Simple Calculator
Microsoft|Largest Product of 3 Elements
FaceBook|Find the k-th Smallest Element in a List
Apple|Maximum Profit From Stocks
Apple|Merge Overlapping Intervals
LinkedIn|Create a Balanced BST
Microsoft|Ways to Traverse a Grid
Google|Deepest Node in a Binary Tree
Facebook|First Missing Positive Integer
Recent Twitter interview problem.
This question has recently emerged. Twitter in the interview.
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.
Given a binary tree, find out the largest binary search tree in its sub-tree and output its nodes in the form of a previous sequence traversal.
Test Case:
Input1:
5
/ \
6 7
/ / \
2 4 9
Output1:
749
// The largest binary search tree is .
7
/ \
4 9
【Here's an ad space.
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
class TreeNode:
def __init__(self, value):
self.left = None
self.right = None
self.value = value
def __str__(self):
The forward sequence traverses the output binary tree.
answer = str(self.value)
if self.left:
answer += str(self.left)
if self.right:
answer += str(self.right)
return answer
class Solution:
def largestBSTSubtree(self, root):
self.maxSize = 0
self.maxRoot = None
def helper(root):
Returns information that a metagroup (size, minValue, maxValue) represents the corresponding sub-tree for the current node.
if root is None:
return (0, float('inf'), float('-inf'))
left = helper(root.left)
right = helper(root.right)
if root.value > left[2] and root.value < right[1]:
size = left[0] + right[0] + 1
if size > self.maxSize:
self.maxSize = size
self.maxRoot = root
return (size, min(root.value, left[1]), max(root.value, right[2]))
else:
return (0, float('-inf'), float('inf'))
helper(root)
return self.maxRoot
# Test Program
# 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(Solution().largestBSTSubtree(node))
# 749
If you have any suggestions for content requirements, or encountered any software, application use problems, please directly in the public number of the main interface to send a private letter to me, I think will reply in a timely manner.Thank you for your support!
Cooperation: classroom.it@hotmail.com
Hi
Hello, sir.
I'm M Xiansen.
This is a platform for learning together.
I'll take it. You want to learn.
Make tutorials or write articles.
We learn English together here.
Learn to program. algorithm.
Learn all kinds of things.
It's fun.Useful software.
Remember to come back often and have a look.
(^_^)a(^_^)a
Click. Read the original text. Check out the Python Algorithm Live Series.
Just order one if you like. Share. Like it. I'm watching. Three companies.Let's go!
Send to the author.