LeetCode: Trim A Binary Search Tree Solution

1/*
2Definition for a binary tree node.
3function TreeNode(val, left, right) {
4 this.val = (val===undefined ? 0 : val)
5 this.left = (left===undefined ? null : left)
6 this.right = (right===undefined ? null : right)
7}
8
9A BST is a BT which every node fit this ordering condition: all left descendents <= n < all right descendents
10*/
11
12var trimBST = function (root, low, high) {
13 if (!root) return root
14 if (root.val > high) return trimBST(root.left, low, high)
15 if (root.val < low) return trimBST(root.right, low, high)
16
17 root.left = trimBST(root.left, low, high)
18 root.right = trimBST(root.right, low, high)
19
20 return root
21}

Comments

Loading comments...

Tags

leetcode

tree

recursion

Apply and earn a $2,500 bonus once you're hired on your first job!

Clients from the Fortune 500 to Silicon Valley startups

Choose your own rate, get paid on time

From hourly, part-time, to full-time positions

Flexible remote working environment

A lot of open JavaScript jobs!!

Fact corner: Referred talent are 5x more likely to pass the Toptal screening process than the average applicant.

Still hesitate? Read HoningJS author's guide on dealing with Toptal interview process.

Next Post

LeetCode: Linked List Cycle

Make used of duck typing

HoningJS

Search Posts