剑指offer_重构二叉树
Posted ~千里之行,始于足下~
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了剑指offer_重构二叉树相关的知识,希望对你有一定的参考价值。
重建二叉树
/**
* 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* reConstructBinaryTree(vector<int> pre,vector<int> vin) {
int n = pre.size();
int m = vin.size();
if(n!=m || n == 0)
return NULL;
return construct(pre, vin, 0, n-1, 0, m-1);
}
TreeNode* construct(vector<int>& pre, vector<int>& vin, int l1, int r1, int l2, int r2)
{
TreeNode* root = new TreeNode(pre[l1]);
if(r1 == l1)
{
return root;
}
int val = pre[l1];
int index;
for(index = l2; index <= r2; index ++)
{
if(vin[index] == val)
break;
}
int left_tree_len = index - l2;
int right_tree_len = r2 - index;
if(left_tree_len > 0)
root->left = construct(pre, vin, l1+1, l1+left_tree_len, l2, index-1);
if(right_tree_len >0 )
root->right = construct(pre, vin, l1+1+left_tree_len, r1, index+1, r2);
return root;
}
};
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
import java.util.Arrays;
public class Solution {
public TreeNode reConstructBinaryTree(int [] pre,int [] vin) {
if (0 == pre.length)
return null;
TreeNode node = new TreeNode(pre[0]);
int rootIndex = -1;
for (int i = 0; i < vin.length; i++)
{
if(pre[0] == vin[i])
{
rootIndex = i;
break;
}
}
node.left = reConstructBinaryTree(Arrays.copyOfRange(pre,1,rootIndex+1),Arrays.copyOfRange(vin,0,rootIndex));
node.right = reConstructBinaryTree(Arrays.copyOfRange(pre,rootIndex+1,pre.length),Arrays.copyOfRange(vin,rootIndex+1,vin.length));
return node;
}
}
# -*- coding:utf-8 -*-
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
# 返回构造的TreeNode根节点
def reConstructBinaryTree(self, pre, vin):
# write code here
if not pre:
return None;
root = TreeNode(pre[0])
tmp = vin.index(pre[0])
root.left = self.reConstructBinaryTree(pre[1:tmp+1], vin[0:tmp])
root.right = self.reConstructBinaryTree(pre[tmp+1:], vin[tmp+1:])
return root
以上是关于剑指offer_重构二叉树的主要内容,如果未能解决你的问题,请参考以下文章