[LeetCode]Construct Binary Tree from Inorder and Postorder Traversal
题目描述:(链接)
Given inorder and postorder traversal of a tree, construct the binary tree.
解题思路:
1 /** 2 * Definition for a binary tree node. 3 * struct TreeNode { 4 * int val; 5 * TreeNode *left; 6 * TreeNode *right; 7 * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 * }; 9 */ 10 class Solution { 11 public: 12 TreeNode* buildTree(vector<int>& inorder, vector<int>& postorder) { 13 return buildTree(begin(inorder), end(inorder), begin(postorder), end(postorder)); 14 } 15 private: 16 TreeNode *buildTree(vector<int>::iterator in_first, vector<int>::iterator in_last, 17 vector<int>::iterator post_first, vector<int>::iterator post_last) { 18 if (in_first == in_last) return nullptr; 19 if (post_first == post_last) return nullptr; 20 21 auto val = *prev(post_last); 22 TreeNode *root = new TreeNode(val); 23 auto in_root_pos = find(in_first, in_last, val); 24 auto in_left_size = distance(in_first, in_root_pos); 25 auto post_left_last = next(post_first, in_left_size); 26 27 root->left = buildTree(in_first, in_root_pos, post_first, post_left_last); 28 root->right = buildTree(next(in_root_pos), in_last, post_left_last, prev(post_last)); 29 30 } 31 };
【推荐】还在用 ECharts 开发大屏?试试这款永久免费的开源 BI 工具!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步