Problem
Given a Binary Search Tree (BST) with root node root, and a target value V, split the tree into two subtrees where one subtree has nodes that are all smaller or equal to the target value, while the other subtree has all nodes that are greater than the target value. It"s not necessarily the case that the tree contains a node with value V.
Additionally, most of the structure of the original tree should remain. Formally, for any child C with parent P in the original tree, if they are both in the same subtree after the split, then node C should still have the parent P.
You should output the root TreeNode of both subtrees after splitting, in any order.
Example 1:
Input: root = [4,2,6,1,3,5,7], V = 2
Output: [[2,1],[4,3,6,null,null,5,7]]
Explanation:
Note that root, output[0], and output[1] are TreeNode objects, not arrays.
The given tree [4,2,6,1,3,5,7] is represented by the following diagram:
4 / 2 6 / / 1 3 5 7
while the diagrams for the outputs are:
4 / 3 6 and 2 / / 5 7 1
Note:
The size of the BST will not exceed 50.
The BST is always valid and each node"s value is different.
class Solution { public TreeNode[] splitBST(TreeNode root, int V) { TreeNode[] res = new TreeNode[2]; if (root == null) return res; if (root.val <= V) { res[0] = root; TreeNode[] rightRes = splitBST(root.right, V); root.right = rightRes[0]; res[1] = rightRes[1]; } else { res[1] = root; TreeNode[] leftRes = splitBST(root.left, V); root.left = leftRes[1]; res[0] = leftRes[0]; } return res; } }
文章版權(quán)歸作者所有,未經(jīng)允許請勿轉(zhuǎn)載,若此文章存在違規(guī)行為,您可以聯(lián)系管理員刪除。
轉(zhuǎn)載請注明本文地址:http://specialneedsforspecialkids.com/yun/72287.html
摘要:題目要求將二叉搜索樹序列化和反序列化,序列化是指將樹用字符串的形式表示,反序列化是指將字符串形式的樹還原成原來的樣子。假如二叉搜索樹的節(jié)點較多,該算法將會占用大量的額外空間。 題目要求 Serialization is the process of converting a data structure or object into a sequence of bits so that...
摘要:思路理論上說所有遍歷的方法都可以。但是為了使和的過程都盡量最簡單,是不錯的選擇。用作為分隔符,來表示。復(fù)雜度代碼思路這道題和之前不同,一般的樹變成了,而且要求是。還是可以用,還是需要分隔符,但是就不需要保存了。 297. Serialize and Deserialize Binary Tree Serialization is the process of converting a...
摘要:解法一中序遍歷分析由于給定了二叉搜索樹,因此首先考慮中序遍歷,使用示例,我們先來分別看一下二叉搜索樹和累加樹中序遍歷的結(jié)果二叉搜索樹二叉累加樹。這里還是使用示例,我們再來觀察一下二叉搜索樹和累加樹中序遍歷的結(jié)果二叉搜索樹二叉累加樹。 ...
摘要:題目意思就是要一個個的返回當(dāng)前的最小值。所以解法自然就是。我們需要找出被打亂的點并返回正確結(jié)果。然后將兩個不正確的點記錄下來,最后回原來正確的值。如果是葉子節(jié)點,或者只有一個子樹。思想來自于的代碼實現(xiàn)。 跳過總結(jié)請點這里:https://segmentfault.com/a/11... BST最明顯的特點就是root.left.val < root.val < root.right.v...
摘要:中序遍歷復(fù)雜度時間空間思路因為左節(jié)點小于根節(jié)點小于右節(jié)點,二叉搜索樹的一個特性就是中序遍歷的結(jié)果就是樹內(nèi)節(jié)點從小到大順序輸出的結(jié)果。這里采用迭代形式,我們就可以在找到第小節(jié)點時馬上退出。這樣我們就可以用二叉樹搜索的方法來解決這個問題了。 Kth Smallest Element in a BST Given a binary search tree, write a function...
閱讀 792·2021-09-22 16:01
閱讀 2085·2021-08-20 09:37
閱讀 1693·2019-08-30 15:54
閱讀 1689·2019-08-30 15:44
閱讀 826·2019-08-28 18:23
閱讀 3005·2019-08-26 12:17
閱讀 1005·2019-08-26 11:56
閱讀 1539·2019-08-23 16:20