For a given binary tree find maximum binary search sub-tree

前端 未结 7 1989
南旧
南旧 2021-02-02 17:34

For a given binary tree, find the largest subtree which is also binary search tree?

Example:

Input:

                   10
               /                


        
7条回答
  •  不知归路
    2021-02-02 17:58

    A binary search tree will give you a sorted result if you do a IN-ORDER Traversal. So, do an in-order traversal for the entire binary tree. The longest sorted sequence is your largest binary search sub tree.

    • Do a inorder traversal of elements (VISIT LEFT, VISIT ROOT, VISIT RIGHT)
    • While doing so, get the node data, compare whether the previous node data is lesser than the next data. If so, increment counter by 1. Store the start node.
    • When the comparison fails, store the end node and reset counter to 0
    • Store this information (counter,start,end) node in an array structure to later find which is having the maximum value and that will give you the longest binary search sub tree

提交回复
热议问题