Day 1 Culture

There was a recent email at work about a new distribution center(DC) opening. What caught my eye in the email from the DC manager was his pride and emphasis on getting the Day 1 culture right…

Smartphone

独家优惠奖金 100% 高达 1 BTC + 180 免费旋转




Check if a Binary Tree is a Binary Search Tree

So to repeat the question here: given a binary tree, check if it is a Binary Search Tree.

To solve this problem, the first thing that would probably come to our mind is to recursively check each node and compare its value and the value of its left child and that of its right child, to make sure left child’s value ≤ node’s value ≤ right child’s value. This is a good start, but it’s not completely right, because in a BST not only the direct children’s values must satisfy the above condition, but also all descendants from the left child must be smaller than or equal to the node’s value, and all descendants from right child must be greater than or equal to it. For example, if the root is 20, its left child is 10, and the left child has its own left child 5 and right child 15, the above condition is satisfied. However, if the left child’s right child has a value 25, this cannot be a BST since 25 is larger than the root value 20.

So how do we make sure that all the descendants on the left and the right side of a root node all satisfies the definition of BST? The In-Order traversal came to our rescue. By definition the In-Order traversal on a BST will visit each node in the correct ascending order. We can thus use such a traversing method, just to modify it a little bit so the recursive calls carry an extra inout parameter that remembers the last visited node’s value.

Here is the code that implements this method, with three test cases of good and bad BSTs included at the end:

and voila, the code does correctly identified true and fake BSTs.

Add a comment

Related posts:

Defiant Soul

A soul becomes defiant when it batters storm time and again, often none for its falter and for reasons beyond its control. When despite possessing goodness and brimming with empathy it is often left…

Why Do You Feel Pain When You Make Love

Have you ever felt a deep pain when you and your loved one were making love? One reason could be that you are suffering from dyspareunia. Many women face such pain. From the very beginning, you need…

I turn 30 tomorrow.

There are 15 words above. I know that because all I’ve done for the past 15 minutes is stare at them, and at a rate of 1 word per minute I think I might fail at my new life as a kitesurfing…