LeetCode 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

-------------------------

Recursive version is easy:

/**
 * 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 *Build(vector& inorder, int s1, int e1,
                  vector& preorder, int s2, int e2) {
    if (s1 > e1)
      return NULL;
    int i, rt_v = preorder[s2];
    TreeNode* rt = new TreeNode(rt_v);
    for (i=0; ileft = lchild;
    rt->right = rchild;
    return rt;
  }
  TreeNode *buildTree(vector &preorder, vector &inorder) {
    // Note: The Solution object is instantiated only once and is reused by each test case.
    return Build(inorder, 0, inorder.size()-1, preorder, 0, preorder.size()-1);   
  }
};

Add iterative version: 

class Solution:
    def buildTree(self, preorder: List[int], inorder: List[int]) -> TreeNode:
        if not preorder:
            return None

        root = TreeNode(preorder[0])
        stack = [root]
        inorderIndex = 0
        for i in range(1, len(preorder)):
            preorderVal = preorder[i]
            node = stack[-1]
            if node.val != inorder[inorderIndex]:
                node.left = TreeNode(preorderVal)
                stack.append(node.left)
            else:
                while stack and stack[-1].val == inorder[inorderIndex]:
                    node = stack.pop()
                    inorderIndex += 1
                node.right = TreeNode(preorderVal)
                stack.append(node.right)

        return root

 

你可能感兴趣的:(python3,leetcode)