【LeetCode】面试题07. 重建二叉树
题目
思路
先序遍历第一个元素就是根结点,中序遍历根节点前面是它的左子树,后边是它的右子树。根据这个思想可以递归的处理,每次得到一个当前阶段的根结点(先序遍历第一个元素),然后根据这个元素将中序遍历划分成两个序列,分别是左子树和右子树的中序遍历,根据这两个序列的长度又可以从先序遍历中得到它们对应的先序遍历。这样就得到了左右子树的先序遍历和中序遍历,递归进行即可。(不含重复数字)
代码
Python
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def buildTree(self, preorder, inorder):
"""
:type preorder: List[int]
:type inorder: List[int]
:rtype: TreeNode
"""
if len(preorder) == 0:
return None
for i in range(len(inorder)):
if inorder[i] == preorder[0]:
break
left_inorder = inorder[0:i]
right_inorder = inorder[i+1:]
left_preorder = preorder[1:1+len(left_inorder)]
right_preorder = preorder[1+len(left_inorder):]
result = TreeNode(preorder[0], self.buildTree(left_preorder, left_inorder), self.buildTree(right_preorder, right_inorder))
return result
C++
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
#include <iostream>
#include <valarray>
#include <cmath>
class Solution {
public:
TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {
return recursionBuild(preorder.begin(),preorder.end(),inorder.begin(),inorder.end());
}
TreeNode* recursionBuild(vector<int>::iterator preBegin, vector<int>::iterator preEnd,vector<int>::iterator inBegin, vector<int>::iterator inEnd )
{
if(inEnd==inBegin) return NULL;
TreeNode* cur = new TreeNode(*preBegin);
auto root = find(inBegin,inEnd,*preBegin);
cur->left = recursionBuild(preBegin+1,preBegin+1+(root-inBegin),inBegin,root);
cur->right = recursionBuild(preBegin+1+(root-inBegin),preEnd,root+1,inEnd);
return cur;
}
};