LeetCode算法题106:从中序与后序遍历序列构造二叉树解析

根据一棵树的中序遍历与后序遍历构造二叉树。

注意:
你可以假设树中没有重复的元素。

例如,给出

中序遍历 inorder = [9,3,15,20,7]
后序遍历 postorder = [9,15,7,20,3]
返回如下的二叉树:

    3
   / \
  9  20
    /  \
   15   7

这个题和上一个题从前序遍历与中序遍历序列构造二叉树思路完全一样。

C++源代码:

/**
 * 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>& inorder, vector<int>& postorder) {
        return buildTree(inorder, 0, inorder.size()-1, postorder, 0, postorder.size()-1);
    }
    
    TreeNode* buildTree(vector<int>& inorder, int iLeft, int iRight, vector<int>& postorder, int pLeft, int pRight){
        if (iLeft > iRight || pLeft > pRight) return NULL;
        int i = 0;
        for (i=iLeft;i<=iRight;i++){
            if (postorder[pRight]==inorder[i]) break;
        }
        TreeNode* cur = new TreeNode(postorder[pRight]);
        cur->left = buildTree(inorder, iLeft, i-1, postorder, pLeft, pLeft+i-iLeft-1);
        cur->right = buildTree(inorder, i+1, iRight, postorder, pLeft+i-iLeft, pRight-1);
        return cur;
    }
};

python3源代码:

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    def buildTree(self, inorder: List[int], postorder: List[int]) -> TreeNode:
        return self.buildTree2(inorder, 0, len(inorder)-1, postorder, 0, len(postorder)-1)
    
    def buildTree2(self, inorder, iLeft, iRight, postorder, pLeft, pRight):
        if iLeft > iRight or pLeft > pRight:
            return None
        i = 0
        for i in range(iLeft, iRight+1):
            if inorder[i]==postorder[pRight]:
                break
        cur = TreeNode(postorder[pRight])
        cur.left = self.buildTree2(inorder, iLeft, i-1, postorder, pLeft, pLeft+i-iLeft-1)
        cur.right = self.buildTree2(inorder, i+1, iRight, postorder, pLeft+i-iLeft, pRight-1)
        return cur

你可能感兴趣的:(Leetcode算法题分析)