首页 > 代码库 > [leetcode] Construct Binary Tree from Preorder and Inorder Traversal
[leetcode] Construct Binary Tree from Preorder and Inorder Traversal
Construct Binary Tree from Preorder and Inorder Traversal
Given preorder and inorder traversal of a tree, construct the binary tree.
Note:
You may assume that duplicates do not exist in the tree.
思路:
由先序遍历和中序遍历确定二叉树的结构。还是那个问题,index-l+i+1是我试出来的,具体为什么需要好好想想。
题解:
/** * Definition for binary tree * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */class Solution {public: void build(vector<int> &preorder, vector<int> &inorder, int l, int r, int index, TreeNode *&root) { if(l>r) return; root = new TreeNode(preorder[index]); int i; for(i=l;i<=r;i++) if(inorder[i]==preorder[index]) break; build(preorder, inorder, l, i-1, index+1, root->left); build(preorder, inorder, i+1, r, index-l+i+1, root->right); } TreeNode *buildTree(vector<int> &preorder, vector<int> &inorder) { if(preorder.size()==0) return NULL; TreeNode *root; build(preorder, inorder, 0, inorder.size()-1, 0, root); return root; }};
[leetcode] Construct Binary Tree from Preorder and Inorder Traversal
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。