Construct Binary Tree from Preorder and Inorder Traversal 前序和中序重建二叉树
2015-04-28 11:17
375 查看
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.
/** * Definition for binary tree * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: TreeNode *buildTree(vector<int> &preorder, vector<int> &inorder) { if(preorder.size()==0|| inorder.size()==0) return NULL; return solve(preorder,0,preorder.size()-1,inorder,0,inorder.size()-1); } TreeNode *solve(vector<int> &preorder,int s1,int e1,vector<int> &inorder,int s2,int e2) { int rootVal=preorder[s1]; int rootIndex=-1; for(int i=s2;i<=e2;i++) if(inorder[i]==rootVal) { rootIndex=i; break; } int left=rootIndex-s2; int right=e2-rootIndex; TreeNode *rootNode=new TreeNode(rootVal); if(left>0) rootNode->left=solve(preorder,s1+1,s1+left,inorder,s2,rootIndex-1); if(right>0) rootNode->right=solve(preorder,s1+left+1,e1,inorder,rootIndex+1,e2); return rootNode; } };
相关文章推荐
- 根据前序和中序序列重建二叉树 Construct Binary Tree from Preorder and Inorder Traversal
- 【构建二叉树】01根据前序和中序序列构造二叉树【Construct Binary Tree from Preorder and Inorder Traversal】
- LeetCode-105:Construct Binary Tree from Preorder and Inorder Traversal (利用先序和中序遍历构建二叉树) -- medium
- LeetCode(Construct Binary Tree from Preorder and Inorder Traversal )根据二叉树的中序遍历和后序遍历重建二叉树
- [LeetCode] 105. Construct Binary Tree from Preorder and Inorder Traversal 由先序和中序遍历建立二叉树
- LeetCode:105_Construct Binary Tree from Preorder and Inorder Traversal | 根据前序和中序遍历构建二叉树 | Medium
- [LintCode] 前序遍历和中序遍历树构造二叉树 Construct Binary Tree from Preorder and Inorder Traversal
- 重建二叉树105. Construct Binary Tree from Preorder and Inorder Traversal
- 根据中序和后序序列重建二叉树 Construct Binary Tree from Inorder and Postorder Traversal
- [LeetCode]108. Construct Binary Tree from Preorder and Inorder Traversal由前序序列和中序序列重建二叉树
- [LeetCode]109. Construct Binary Tree from Inorder and Postorder Traversal由中序序列和后序序列重建二叉树
- 105\106. Construct Binary Tree from Inorder and Postorder\Preorder Traversal&重建二叉树
- Construct Binary Tree from Preorder and Inorder Traversal 从先序和中序重建二叉树@LeetCode
- 【LeetCode笔记】Construct Binary Tree from Preorder and Inorder Traversal 前序、中序还原二叉树
- 经典:Construct Binary Tree from Preorder and Inorder Traversal:由先序中序构建二叉树
- Construct Binary Tree from Inorder and Postorder Traversal 中序和后序重建二叉树
- Construct Binary Tree from Inorder and Postorder Traversal 由中序和后序重建二叉树@LeetCode
- 剑指offer 面试题6:重建二叉树(Leetcode105. Construct Binary Tree from Preorder and Inorder Traversal) 解题报告
- <leetcode> 105. Construct Binary Tree from Preorder and Inorder Traversal 重建二叉树
- Leetcode 106. Construct Binary Tree from Inorder and Postorder Traversal 中序和后序恢复二叉树