`

Zenefits Interview - A pair with given sum in a Balanced BST

 
阅读更多

Find two elements in balanced BST which sums to a given a value. Constraints Time O(n) and space O(log n).

 

The Brute Force Solution is to consider each pair in BST and check whether the sum equals to X. The time complexity of this solution will be O(n^2).

 

A Better Solution is to create an auxiliary array and store Inorder traversal of BST in the array. The array will be sorted as Inorder traversal of BST always produces sorted data. Once we have the Inorder traversal, we can pair in O(n) time. This solution works in O(n) time, but requires O(n) auxiliary space.

 

The idea is same as finding the pair in sorted array. We traverse BST in Normal Inorder and Reverse Inorder simultaneously. In reverse inorder, we start from the rightmost node which is the maximum value node. In normal inorder, we start from the left most node which is minimum value node. We add sum of current nodes in both traversals and compare this sum with given target sum. If the sum is same as target sum, we return true. If the sum is more than target sum, we move to next node in reverse inorder traversal, otherwise we move to next node in normal inorder traversal. If any of the traversals is finished without finding a pair, we return false. Following is Java implementation of this approach.

 

public int[] findPair(TreeNode root, int target) {
	int[] pair = new int[]{-1, -1};
	Stack<TreeNode> leftStack = new Stack<>();
	Stack<TreeNode> rightStack = new Stack<>();
	boolean searchLeft = true, searchRight = true;
	TreeNode leftNode = root, rightNode = root;
	int leftVal = 0, rightVal = 0;
	while(true) {
		while(searchLeft) {
			if(leftNode != null) {
				leftStack.push(leftNode);
				leftNode = leftNode.left;
			} else {
				searchLeft = false;
				if(!leftStack.isEmpty()) {
					leftNode = leftStack.pop();
					leftVal = leftNode.val;
					leftNode = leftNode.right;
				}
			}
		}
		while(searchRight) {
			if(rightNode != null) {
				rightStack.push(rightNode);
				rightNode = rightNode.right;
			} else {
				searchRight = false;
				if(!rightStack.isEmpty()) {
					rightNode = rightStack.pop();
					rightVal = rightNode.val;
					rightNode = rightNode.left;
				}
			}
		}
		if(leftVal >= rightVal) {
			return pair;
		}
		if(leftVal + rightVal == target) {
			pair[0] = leftVal;
			pair[1] = rightVal;
			return pair;
		} else if(leftVal + rightVal > target) {
			searchRight = true;
		} else {
			searchLeft = true;
		}
	}
}

 

Reference:

http://www.geeksforgeeks.org/find-a-pair-with-given-sum-in-bst/

http://www.geeksforgeeks.org/find-if-there-is-a-triplet-in-bst-that-adds-to-0/

分享到:
评论

相关推荐

    Photonics-based radar with balanced I/Q de-chirping for interference-suppressed high-resolution detection and imaging

    In this paper, we propose a photonics-based radar with a photonic frequency-doubling transmitter and a balanced in-phase and quadrature (I/Q) de-chirp receiver. This radar transmits broadband ...

    英文原版-Mobile App Development with Ionic 2 1st Edition

    Cross-Platform Apps with Ionic 2, Angular 2, and Cordova.With Early Release ebooks, you get books in their earliest form—the author's raw and unedited content as he or she writes—so you can take ...

    英文原版-Problem Solving and Program Design in C 7th Edition

    The book provides a gradual introduction to pointers and covers programming with functions early in the text. In later chapters, students learn to implement fundamental data structures such as lists,...

    Microservice Patterns - With examples in java - first version

    Rather than simply advocating for the use the microservice architecture, this clearly-written guide takes a balanced, pragmatic approach, exploring both the benefits and drawbacks.

    非常优秀的PCB设计辅助工具

    Calculates the differential pair impedance of a balanced line. PCB Padstack Calculator Calculates the outer and inner layer diameters of a padstack given the drill size. BGA land calculator based on ...

    BST.rar_bst_in

    5. **平衡因子和平衡二叉搜索树 (Balanced BST)**:常规BST在最坏的情况下可能退化成链表,导致性能下降。为解决这个问题,引入了AVL树和红黑树等自平衡BST,它们通过特定规则保持树的平衡,确保查找、插入和删除的...

    Laravel开发-laravel-balanced

    **Laravel 开发框架详解——基于 Laravel-balanced 的实践** Laravel 是一款广泛使用的开源 PHP 框架,以其优雅的语法和强大的功能深受开发者喜爱。在 Laravel 的生态系统中,`laravel-balanced` 是一个特定的扩展...

    Agreement on Target-Bidirectional LSTMs for Sequence-to-Sequence Learning

    agreement between a pair of target-directional LSTMs, which generates more balanced targets. In addition, we develop two efficient approximate search methods for agreement that are empirically shown ...

    A Balanced-to-Balanced Power Divider With Wide Bandwidth

    本研究提出了一种新型平衡至平衡功率分配器(Balanced-to-Balanced Power Divider, B2B PD),该设计通过在背对背微带Wilkinson PD的公共地面上蚀刻槽和开孔来实现。这种方法不仅能够保持功率分配器的基本功能,还...

    Energy-balanced Multiple-sensor collaborative scheduling

    An energy-balanced multiple-sensor collaborative scheduling is proposed for maneuvering target tracking in wireless sensor networks (WSNs). According to the position of the maneuvering target, some ...

    ISTA_Procedure_2A_08-08.pdf

    Inch-Pound units are shown first with Metric units in brackets, except in some tables where they are shown separately. • Either system may be used as the unit of measure (standard units), but • ...

    LeetCode最全代码

    421 | [Maximum XOR of Two Numbers in an Array](https://leetcode.com/problems/maximum-xor-of-two-numbers-in-an-array/) | [C++](./C++/maximum-xor-of-two-numbers-in-an-array.cpp) [Python](./Python/...

    java-leetcode-110-balanced-binary-tree

    java java_leetcode-110-balanced-binary-tree

    map-for-c-by-balanced-binary-tree

    在这个场景中,我们关注的是一个用C语言实现的特定版本,它基于平衡二叉树(Balanced Binary Tree)来实现Map。平衡二叉树是一种特殊的二叉树,它的每个节点都包含一个键和一个关联的值,同时树的高度保持平衡,这...

    leetcode中国-leetcode-experience:zpxuleetcode体验

    leetcode中国 ...(split-a-string-in-balanced-strings) 595. 大的国家 (big-countries) 1021. 删除最外层的括号 (remove-outermost-parenthese) 2019/12/7 938. 二叉搜索树的范围和 (range-sum-of-bst)

    英语作文经典模板.doc

    例如,"In recent years, we are faced with a problem --------A, which is being more and more serious. First, -----. Second, -----. Last but not least, -----." 接着,作者阐述面对问题应采取的有效措施。...

    Balanced-binary-tree.rar_Balanced Binary Tree

    在本项目中,“Balanced-binary-tree.rar”是一个压缩包,包含了一个C++实现平衡二叉树的实例,对于学习C++编程以及理解数据结构的深度是很有帮助的。 平衡二叉树分为几种类型,如AVL树和红黑树。AVL树是最先被提出...

    A DC-Balanced, Partitioned-Block, 8B-1OB Transmission Code.pdf

    “A DC-Balanced, Partitioned-Block, 8B-10B Transmission Code”是一篇由A.X. Widmer与P.A. Franaszek共同撰写的论文,主要介绍了在高速局域网络和类似数据链路中应用的一种高效的数据传输编码技术——8B/10B编码...

Global site tag (gtag.js) - Google Analytics