首页 > 代码库 > Construct Binary Tree from Inorder and Postorder Traversal
Construct Binary Tree from Inorder and Postorder Traversal
Construct Binary Tree from Inorder and Postorder Traversal
Given inorder and postorder traversal of a tree, construct the binary tree.
根据后序遍历和中序遍历构建一棵二叉树
/** * 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: void Build(int l1, int r1, int l2, int r2, const vector<int>& post, const vector<int> & in, TreeNode*& root){ int i; for ( i = l2; i <= r2; i++) { if (in[i] == post[r1]) break; } root = new TreeNode(post[r1]); if (i == l2) root->left = NULL; else Build(l1, l1 + i - l2 - 1, l2, i - 1,post, in,root->left); //边界条件 if (i == r2) root->right = NULL; else Build(l1+i-l2, r1 - 1, i + 1, r2,post, in, root->right); //边界条件 } TreeNode* buildTree(vector<int>& inorder, vector<int>& postorder) { if(postorder.size()==0 && inorder.size()==0) return nullptr; TreeNode* root; Build(0,postorder.size()-1, 0, inorder.size()-1, postorder, inorder, root); return root; } };
Construct Binary Tree from Inorder and Postorder Traversal
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。