1008. Construct Binary Search Tree from Preorder Traversal

Link: https://leetcode.com/problems/construct-binary-search-tree-from-preorder-traversal/

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.)

Example 1:

Input: [8,5,1,7,10,12]
Output: [8,5,10,1,7,null,12]

1

Note:

  • 1 <= preorder.length <= 100
  • The values of preorder are distinct.

題目翻譯:

返回與給定的前序遍歷匹配的二叉搜索樹的根節點。

(回想一下二進制搜索樹是一個二叉樹,對於每個節點,node.left 的任何後代都有一個值 node.val。還記得那個 preorder 遍歷首先顯示節點的值,然後遍歷 node.left,然後遍歷 node.right。)

程式思路:
這題是用印出來的 preoder 去逆推原本樹的樣子。node 先,再來 left 再來 right,其實就只是把元素按照大小做簡單的插入分類就能解題了。

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    void tree_insert(TreeNode **node,int val)
    {
        if(*node == nullptr )
        {
            *node = new TreeNode(val);
            return;
        }
        TreeNode *pre,*cur = *node;
        while(cur)
        {
            pre = cur;
            cur = (val < cur->val) ? cur->left : cur->right;
        }
        if(val > pre->val )
            pre->right = new TreeNode(val);
        else if(val < pre->val )
            pre->left = new TreeNode(val);
    }
    TreeNode* bstFromPreorder(vector<int>& preorder) {
        TreeNode *root = nullptr;

        for(auto val : preorder)
        {
            tree_insert(&root,val);
        }
        return root;
    }
};

  目錄