本文主要是介绍Leetcode 106 Construct Binary Tree from Inorder and Postorder Traversal(二叉树),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
题目连接:Leetcode 106 Construct Binary Tree from Inorder and Postorder Traversal
解题思路:参考 Leetcode 105。
/*** 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>& inorder, vector<int>& postorder) {if (start > end) return NULL;TreeNode* ret = new TreeNode(postorder[p--]);if (start == end) return ret;int t = start;while (t <= end && inorder[t] != postorder[p+1]) t++;ret->right = build(p, t+1, end, inorder, postorder);ret->left = build(p, start, t-1, inorder, postorder);return ret;}TreeNode* buildTree(vector<int>& inorder, vector<int>& postorder) {int p = postorder.size() - 1;return build(p, 0, inorder.size()-1, inorder, postorder);}
};
这篇关于Leetcode 106 Construct Binary Tree from Inorder and Postorder Traversal(二叉树)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!