leetcode 105. Construct Binary Tree from Preorder and Inorder Traversal

来源:互联网 发布:优化人才培养方案 编辑:程序博客网 时间:2024/06/06 17:48

分析见:http://blog.csdn.net/kexiii/article/details/55254802


class Solution {public:TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder){if (inorder.empty()){return nullptr;}auto PreIndex = 0, InIndex = 0;auto root = new TreeNode(preorder[PreIndex++]);stack<TreeNode*> stack;stack.push(root);while (true){if (stack.top()->val != inorder[InIndex]){auto p = new TreeNode(preorder[PreIndex++]);stack.top()->left = p;stack.push(p);}else{auto p = stack.top();stack.pop();InIndex++;if (InIndex == inorder.size()){break;}if (stack.size() && stack.top()->val == inorder[InIndex]){continue;}p->right = new TreeNode(preorder[PreIndex++]);stack.push(p->right);}}return root;}};




0 0
原创粉丝点击