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/
相关推荐
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 ...
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 ...
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,...
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.
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 ...
5. **平衡因子和平衡二叉搜索树 (Balanced BST)**:常规BST在最坏的情况下可能退化成链表,导致性能下降。为解决这个问题,引入了AVL树和红黑树等自平衡BST,它们通过特定规则保持树的平衡,确保查找、插入和删除的...
**Laravel 开发框架详解——基于 Laravel-balanced 的实践** Laravel 是一款广泛使用的开源 PHP 框架,以其优雅的语法和强大的功能深受开发者喜爱。在 Laravel 的生态系统中,`laravel-balanced` 是一个特定的扩展...
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 ...
本研究提出了一种新型平衡至平衡功率分配器(Balanced-to-Balanced Power Divider, B2B PD),该设计通过在背对背微带Wilkinson PD的公共地面上蚀刻槽和开孔来实现。这种方法不仅能够保持功率分配器的基本功能,还...
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 ...
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 • ...
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 java_leetcode-110-balanced-binary-tree
在这个场景中,我们关注的是一个用C语言实现的特定版本,它基于平衡二叉树(Balanced Binary Tree)来实现Map。平衡二叉树是一种特殊的二叉树,它的每个节点都包含一个键和一个关联的值,同时树的高度保持平衡,这...
leetcode中国 ...(split-a-string-in-balanced-strings) 595. 大的国家 (big-countries) 1021. 删除最外层的括号 (remove-outermost-parenthese) 2019/12/7 938. 二叉搜索树的范围和 (range-sum-of-bst)
例如,"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”是一个压缩包,包含了一个C++实现平衡二叉树的实例,对于学习C++编程以及理解数据结构的深度是很有帮助的。 平衡二叉树分为几种类型,如AVL树和红黑树。AVL树是最先被提出...
“A DC-Balanced, Partitioned-Block, 8B-10B Transmission Code”是一篇由A.X. Widmer与P.A. Franaszek共同撰写的论文,主要介绍了在高速局域网络和类似数据链路中应用的一种高效的数据传输编码技术——8B/10B编码...