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.
這道題給了我們一棵二叉搜索樹Binary Search Tree,又給了我們一個目標值V,讓我們將這個BST分割成兩個子樹,其中一個子樹所有結點的值均小於等於目標值V,另一個子樹所有結點的值均大於目標值V。這道題最大的難點在於不是簡單的將某條邊斷開就可以的,不如題目中給的那個例子,目標值為2,我們知道要斷開結點2和結點4的那條邊,但是以結點2為root的子樹中是有大於目標值2的結點的,而這個結點3必須也從該子樹中移出,並加到較大的那個子樹中去的。為了具體的講解這個過程,這里借用官方解答貼中的例子來說明問題吧。
比如對於上圖,假如root結點小於V,而root.right大於V的話,那么這條邊是要斷開的,但是如果root.right的左子結點(結點A)是小於V的,那么其邊也應該斷開,如果如果root.right的左子結點的右子結點(結點B)大於V,則這條邊也應該斷開,所以總共有三條邊需要斷開,如圖中藍色虛線所示,三條粗灰邊需要斷開,粉細邊和綠細邊是需要重新連上的邊。那么我們應該如何知道連上哪條邊呢?不要急,聽博主慢慢道來。
博主告訴你們個秘密(一般人我不告訴他),對於樹的題目,二話別說,直接上遞歸啊,除非是有啥特別要求,否則遞歸都可以解。而遞歸的精髓就是不斷的DFS進入遞歸函數,直到遞歸到葉結點,然后回溯,我們遞歸函數的返回值是兩個子樹的根結點,比如對結點A調用遞歸,返回的第一個是A的左子結點,第二個是結點B,這個不需要重新連接,那么當回溯到root.right的時候,我們就需要讓root.right結點連接上結點B,而這個結點B是對結點A調用遞歸的返回值中的第二個。如果是在左邊,其實是對稱的,root.left連接上調用遞歸返回值中的第一個,這兩個想通了后,代碼就不難謝啦,參見代碼如下:
class Solution { public: vector<TreeNode*> splitBST(TreeNode* root, int V) { vector<TreeNode*> res{NULL, NULL}; if (!root) return res; if (root->val <= V) { res = splitBST(root->right, V); root->right = res[0]; res[0] = root; } else { res = splitBST(root->left, V); root->left = res[1]; res[1] = root; } return res; } };
類似題目:
參考資料:
https://leetcode.com/problems/split-bst/solution/
https://leetcode.com/problems/split-bst/discuss/113798/C++Easy-recursion-in-O(n)