欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

105. Construct Binary Tree from Preorder and Inorder Traversal

程序员文章站 2022-03-03 10:12:53
...

105. 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.

For example, given

preorder = [3,9,20,15,7]
inorder = [9,3,15,20,7]
Return the following binary tree:

    3
   / \
  9  20
    /  \
   15   7

方法1:

basketking:https://www.youtube.com/watch?v=S1wNG5hx-30

思路:

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution1 {
public:
    TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {
        int preStart = 0;
        int inStart = 0;
        int inEnd = preorder.size() - 1;
        if (preorder.size() == 0) return NULL;
        
        return helper(preorder, inorder, preStart, inStart, inEnd);
    }
    
    TreeNode* helper(vector<int> & preorder, vector<int> & inorder, int preStart, int inStart, int inEnd){
        // ending case is inStart > inEnd
        // happen when the child node is null
        // current will create the leaf node;
        if (preStart >= preorder.size()|| inStart > inEnd) return NULL;
       
        
        TreeNode* current = new TreeNode(preorder[preStart]);
       
        int k;
         
        for (int i = inStart; i <= inEnd; i++){
            if (preorder[preStart] == inorder[i]){
                k = i;
                break;  
            }
        }
        // i is the position of preorder[preStart] in inorder
        
        current->left = helper(preorder, inorder, preStart + 1, inStart, k - 1);
        current->right = helper(preorder, inorder, preStart + (k - inStart) + 1, k + 1, inEnd);
        return current;
    }
};