Return the root node of a binary search tree that matches the given preorder
traversal.
(Recall that a binary search tree is a binary tree where for every node, any descendant of node.left
has a value <
node.val
, and any descendant of node.right
has a value >
node.val
. Also recall that a preorder traversal displays the value of the node
first, then traverses node.left
, then traverses node.right
.)
It's guaranteed that for the given test cases there is always possible to find a binary search tree with the given requirements.
Example 1:
Input: [8,5,1,7,10,12]
Output: [8,5,10,1,7,null,12]
Constraints:
1 <= preorder.length <= 100
1 <= preorder[i] <= 10^8
- The values of
preorder
are distinct.
這道題讓我們從一個數組來重建一棵二叉搜索樹,同時說明了這個數組是先序遍歷二叉樹后得到的。首先要明白的是二叉搜索樹的性質,是左子結點值小於根結點小於右子結點,正是因為有這樣的特點,才使得從一種遍歷順序上重建變的可能。若是普通的二叉樹,則至少需要兩種遍歷順序的數組,比如之前的 Construct Binary Tree from Preorder and Postorder Traversal,Construct Binary Tree from Inorder and Postorder Traversal,和 Construct Binary Tree from Preorder and Inorder Traversal。再來分析下這個先序數組有什么特點,先序是根左右的順序,則第一個結點肯定是根結點,而根據二叉搜索樹的特點,接下來第一個大於根結點值的數一定是右子結點,而中間的數字都是左子樹中的值,這樣就可以將左右子樹分開了,再分別調用遞歸函數就可以建成整個樹了。有了思路,代碼就很好寫了,先對 preorder 判空,若不為空則用第一個數字建立一個根結點,然后遍歷數組,找到第一個大於根結點值的數字,將左右子樹的數組提取來,分別調用遞歸函數,連接到根結點的左右子結點即可,參見代碼如下:
class Solution {
public:
TreeNode* bstFromPreorder(vector<int>& preorder) {
if (preorder.empty()) return nullptr;
TreeNode *node = new TreeNode(preorder[0]);
int i = 0, n = preorder.size();
for (i = 1; i < n; ++i) {
if (preorder[i] > preorder[0]) break;
}
vector<int> left(preorder.begin() + 1, preorder.begin() + i);
vector<int> right(preorder.begin() + i, preorder.end());
node->left = bstFromPreorder(left);
node->right = bstFromPreorder(right);
return node;
}
};
Github 同步地址:
https://github.com/grandyang/leetcode/issues/1008
類似題目:
Construct Binary Tree from Preorder and Postorder Traversal
Construct Binary Tree from Inorder and Postorder Traversal
Construct Binary Tree from Preorder and Inorder Traversal
參考資料:
https://leetcode.com/problems/construct-binary-search-tree-from-preorder-traversal/