• 1008. Construct Binary Search Tree from Preorder Traversal


    Given an array of integers preorder, which represents the preorder traversal of a BST (i.e., binary search tree), construct the tree and return its root.

    It is guaranteed that there is always possible to find a binary search tree with the given requirements for the given test cases.

    binary search tree is a binary tree where for every node, any descendant of Node.left has a value strictly less than Node.val, and any descendant of Node.right has a value strictly greater than Node.val.

    preorder traversal of a binary tree displays the value of the node first, then traverses Node.left, then traverses Node.right.

    Example 1:

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

    Example 2:

    Input: preorder = [1,3]
    Output: [1,null,3]

    题目:给定一个二叉查找树的preorder排序数组,让还原出这个二叉查找树

    思路,与654. Maximum Binary Tree思路很像,用栈来保存每个节点,不同的是,本题是以大小来判断左右子树,而654是以位置来判断左右子树。代码:

    1. /**
    2. * Definition for a binary tree node.
    3. * struct TreeNode {
    4. * int val;
    5. * TreeNode *left;
    6. * TreeNode *right;
    7. * TreeNode() : val(0), left(nullptr), right(nullptr) {}
    8. * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
    9. * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
    10. * };
    11. */
    12. class Solution {
    13. public:
    14. TreeNode* bstFromPreorder(vector<int>& preorder) {
    15. stack stk;
    16. TreeNode* head = new TreeNode(preorder[0]);
    17. stk.push(head);
    18. for(int i = 1; i < preorder.size(); i++){
    19. TreeNode* node = new TreeNode(preorder[i]);
    20. if(stk.top()->val > preorder[i]){
    21. stk.top()->left = node;
    22. } else {
    23. TreeNode* top = stk.top();
    24. while(!stk.empty() && stk.top()->val < preorder[i]){
    25. top = stk.top();
    26. stk.pop();
    27. }
    28. top->right = node;
    29. }
    30. stk.push(node);
    31. }
    32. return head;
    33. }
    34. };

    时间:O(N), 空间:O(N)

  • 相关阅读:
    Qt学习记录___9.10
    JVM虚拟机浅谈(四)
    测试路由器
    有哪些原因会导致excel文档损坏打不开?
    基于SpringBoot的的师生健康信息管理系统
    visual studio 启用C++11
    计算机毕业设计 基于SSM+Vue的农业信息管理系统的设计与实现 Java实战项目 附源码+文档+视频讲解
    python获取时间戳
    idea项目打开,module模块中图标没有 maven 的标志
    浅析网络编程
  • 原文地址:https://blog.csdn.net/qing2019/article/details/126172875