标签:
本系列文章已全部上传至我的github,地址:ZeeCoder‘s Github
欢迎大家关注我的新浪微博,我的新浪微博
欢迎转载,转载请注明出处
来源:https://leetcode.com/problems/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.
题目大意:根据二叉树的前序和中序遍历,构造出该二叉树
剑指offer上的老题了,前序遍历的第一个节点为根节点,在中序遍历中找到该节点,其左边为根节点的左子树,后边为根节点的右子树。依次递归下去即可以重构出该二叉树。
如:123和213,前序遍历找出根节点为1,在中序遍历213中找出1,则2为左子树,3为右子树。
/**
* 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:
typedef vector<int>::iterator vi;
TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {
if(preorder.empty()||inorder.empty()) return (TreeNode*)NULL;
vi preStart = preorder.begin();
vi preEnd = preorder.end()-1;
vi inStart = inorder.begin();
vi inEnd = inorder.end()-1;
return constructTree(preStart,preEnd,inStart,inEnd);
}
TreeNode* constructTree(vi preStart,vi preEnd,vi inStart,vi inEnd)
{
//表示该节点为NULL
if(preStart>preEnd||inStart>inEnd) return NULL;
//前序遍历的第一个节点为根节点
TreeNode* root = new TreeNode(*preStart);
//只有一个节点的时候直接返回
if(preStart==preEnd||inStart==inEnd) return root;
vi rootIn = inStart;
while(rootIn!=inEnd){//在中序遍历中找出根节点
if(*rootIn==*preStart) break;
else ++rootIn;
}
root->left = constructTree(preStart+1,preStart+(rootIn-inStart),inStart,rootIn-1);//递归构造左子树
root->right = constructTree(preStart+(rootIn-inStart)+1,preEnd,rootIn+1,inEnd);//递归构造右子树
return root;
}
};
【一天一道LeetCode】#105. Construct Binary Tree from Preorder and Inorder Traversal
标签:
原文地址:http://blog.csdn.net/terence1212/article/details/51779174