Leetcode 105. previous order and sequence preorder binary tree configuration and the C ++ implementation solving ideas

Problem-solving ideas:

Preorder traversal to the preamble, the first is the root node, then the node inorder traversal sequence found in the corresponding, the previous value of that node inorder both the left subtree of the root node, the node values ​​are back at right sub-tree root node, you can use recursion to build a binary tree, each node to its left subtree, right subtree of node build number.

 

/**
 * 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:
    TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {
        return conTree(preorder, 0, preorder.size()-1, inorder, 0, inorder.size()-1);
    }
    TreeNode* conTree(vector<int>& preorder, int pl, int pr, vector<int>& inorder, int il, int ir){
        if(pl > pr || il > ir)
            return NULL;
        TreeNode* root = new TreeNode(preorder[pl]);
        for(int i = il; i <= ir; i++){
            if(preorder[pl] == inorder[i]){
                root->left = conTree(preorder, pl+1, pl+i-il, inorder, il, i-1);
                root->right = conTree(preorder, pl+i-il+1, pr, inorder, i+1, ir);
                break;
            }
        }
        return root;
    }
};

 

 

Guess you like

Origin blog.csdn.net/gjh13/article/details/92164684