本文主要是介绍Leetcode 105 Construct Binary Tree from Preorder and Inorder Traversal(二叉树),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
题目连接:Leetcode 105 Construct Binary Tree from Preorder and Inorder Traversal
解题思路:p指针在二叉树的中序遍历上移动,inorder[p]即为当前结点的值,然后找到preorder中找到inorder[p]的位置t,根据前序遍历的性质,在preorder中,start~t-1的结点应该是当前结点的左子树,t+1~end的结点应该是当前结点右子树。先构建左子树,后构建右子树,保证p在inorder中的移动顺序。
/*** 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:TreeNode* build(int& p, int start, int end, vector<int>& preorder, vector<int>& inorder) {if (start > end) return NULL;TreeNode* ret = new TreeNode(preorder[p++]);if (start == end) return ret;int t = start;while (t <= end && inorder[t] != preorder[p-1]) t++;ret->left = build(p, start, t-1, preorder, inorder);ret->right = build(p, t+1, end, preorder, inorder);return ret;}TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {int p = 0;return build(p, 0, inorder.size()-1, preorder, inorder);}
};
这篇关于Leetcode 105 Construct Binary Tree from Preorder and Inorder Traversal(二叉树)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!