[geeks]Construct BST from given preorder traversal——iterative solution
来源:互联网 发布:linux解包system.img 编辑:程序博客网 时间:2024/05/23 11:25
步骤:
1、建立一个空栈
2、使preorder数组中的第一个元素为root,并把root推入栈中
3、重复下面步骤直到遍历完preorder数组
如果当前preorder数组中的元素大于栈中节点的值,pop栈顶元素,直到栈为空,或者栈顶节点的值大于preorder数组中的元素。令最后被pop出来的节点的右子树为当前元素,并将其push入栈。
如果当前元素小于栈顶节点的值,那么令栈顶节点的左子树为当前节点,并将其push入栈。
struct TreeNode {int val;TreeNode *left;TreeNode *right;TreeNode(int x) : val(x), left(NULL), right(NULL) {}};class Solution {public:TreeNode *buildTree(vector<int> &preorder) {/*O(n)非递归*/stack<TreeNode*> myStack;TreeNode *root = new TreeNode(preorder[0]);myStack.push(root);for(int i = 1; i < preorder.size(); ++i){TreeNode *tmp = NULL;while(!myStack.empty() && preorder[i] > myStack.top()->val)tmp = myStack.top(), myStack.pop();if(tmp != NULL){tmp->right = new TreeNode(preorder[i]);myStack.push(tmp->right);}else{myStack.top()->left = new TreeNode(preorder[i]);myStack.push(myStack.top()->left);}}return root;}};
- [geeks]Construct BST from given preorder traversal——iterative solution
- [geeks]Construct BST from given preorder traversal
- Construct a special tree from given preorder traversal
- [LeetCode] Construct Binary Tree from Preorder and Inorder Traversal, Solution
- [geeks]Construct Full Binary Tree from given preorder and postorder traversals
- LeetCode105—Construct Binary Tree from Preorder and Inorder Traversal
- leetcode 105. Construct Binary Tree from Preorder and Inorder Traversal 中前序构造BST
- Lintcode73 Construct Binary Tree from Preorder and Inorder Traversal solution 题解
- Lintcode73 Construct Binary Tree from Preorder and Inorder Traversal solution 题解
- leetcode——105——Construct Binary Tree from Preorder and Inorder Traversal
- LeetCode——Construct Binary Tree from Preorder and Inorder Traversal
- leetcode 105 —— Construct Binary Tree from Preorder and Inorder Traversal
- 【leetcode】Array——Construct Binary Tree from Preorder and Inorder Traversal(105)
- LeetCode刷题(C++)——Construct Binary Tree from Preorder and Inorder Traversal(Normal)
- 5.2.1—二叉树的构建—Construct Binary Tree from Preorder and Inorder Traversal
- LeetCode——105. Construct Binary Tree from Preorder and Inorder Traversal
- Algorithms—105.Construct Binary Tree from Preorder and Inorder Traversal
- Construct Full Binary Tree from given preorder and postorder traversals
- Eclipse中@author的修改
- acmore 1510: ZZ love Cookies
- 递归实现的全排列算法
- 类的内存存储区域
- 物理模型
- [geeks]Construct BST from given preorder traversal——iterative solution
- 实验任务四
- Linux iptables 防火墙 添加删除 端口
- iOS Framework 制作教程
- 实验任务五
- ubuntu13.04安装OpenStack Grizzly
- Liunx下Shell脚本执行
- rep stos dword ptr es:[edi] 是做什么的?
- 1.引言-为什么使用F#