Tuesday, February 2, 2021

Remove all the nodes in BST which are not in a range

Problem: Given a binary search tree and a range [low, high] where low being the lowest and high being the highest boundaries of the range, trim the tree so that all its elements lies in [low, high]. Trimming the tree should not change the relative structure of the elements that will remain in the tree. 

Example:


Input: low = 2, high = 3


Approach: We can use Pre Order traversal to solve this problem. Approach is straight forward and can be understood by just looking at the code.


Implementation in C#:

        public void TrimBST(int low, int high)

        {

            if (this.Root == null)

            {

                return;

            }

            this.Root = this.TrimBST(this.Root, low, high);

        }


        private BinaryTreeNode TrimBST(BinaryTreeNode node, int low, int high)

        {

            if (node == null)

            {

                return null;

            }

            if (node.Value > high)

            {

                return this.TrimBST(node.LeftNode, low, high);

            }            

            if (node.Value < low)

            {

                return this.TrimBST(node.RightNode, low, high);

            }

            node.LeftNode = this.TrimBST(node.LeftNode, low, high);

            node.RightNode = this.TrimBST(node.RightNode, low, high);

            return node;

        }


Complexity: O(n)

No comments:

Post a Comment