To prove safety offer- tree - reconstruction of a binary tree

Title Description

And enter the result in a preorder traversal of a binary tree in preorder traversal of the binary tree a rebuild. Suppose Results preorder traversal order and input of duplicate numbers are free. Before entering e.g. preorder traversal sequence {1,2,4,7,3,5,6,8} and {4,7,2,1,5,3,8,6} order traversal sequence, and the reconstructed binary tree return.

analysis

No repeating numbers.

Preorder traversal of a sequence of values ​​is the root node, in order to find its location in the traversal, that this location is in front of the left subtree node, right node is the right subtree. The number of sibling nodes, the root node can find the left and right subtrees of the previous traversal order. Recursion, binary tree reconstruction.

Code

/**
 * 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) {
        TreeNode *root = reBuildTree(pre, 0, pre.size()-1, vin, 0, vin.size()-1);
        return root;
    }
    TreeNode* reBuildTree(vector<int> pre,int startPre,int endPre,vector<int>in,int startIn,int endIn) {
        if(startPre>endPre || startIn > endIn)
            return nullptr;
        TreeNode *root = new TreeNode(pre[startPre]);
        for(int i = startIn; i <= endIn; i++) {
            if(in[i] == pre[startPre]) {
                root->left = reBuildTree(pre,startPre+1,startPre+i-startIn,in,startIn,i-1);
                root->right = reBuildTree(pre,i-startIn+startPre+1,endPre,in,i+1,endIn);
                break;
            }
        }
        return root;
    }
};

 

Published 35 original articles · won praise 6 · views 6690

Guess you like

Origin blog.csdn.net/qq_35413770/article/details/105178277