LintCode(72)中序遍历和后序遍历树构造二叉树

Posted 逆風的薔薇

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LintCode(72)中序遍历和后序遍历树构造二叉树相关的知识,希望对你有一定的参考价值。

题目

 中序遍历和后序遍历树构造二叉树

根据中序遍历和后序遍历树构造二叉树

样例

给出树的中序遍历: [1,2,3] 和后序遍历: [1,3,2]

返回如下的树:

  2

 /  \

1    3

分析

递归解决。

Python代码

"""
Definition of TreeNode:
class TreeNode:
    def __init__(self, val):
        self.val = val
        self.left, self.right = None, None
"""
def buildSubTree(inorder, inBeg, inEnd, postorder, postBeg, postEnd):
    inLen = len(inorder)
    postLen = len(postorder)
    if inBeg == inEnd or inEnd > inLen or postBeg == postEnd or postEnd > postLen:
        return None

    root = TreeNode(postorder[postEnd - 1])
    pos = inorder.index(root.val)

    leftLen = pos - inBeg - 1
    root.left = buildSubTree(inorder, inBeg, inBeg + leftLen + 1, postorder, postBeg, postBeg + leftLen + 1)
    root.right = buildSubTree(inorder, inBeg + leftLen + 2, inEnd, postorder, postBeg + leftLen + 1, postEnd - 1)

    return root


class Solution:
    """
    @param inorder : A list of integers that inorder traversal of a tree
    @param postorder : A list of integers that postorder traversal of a tree
    @return : Root of a tree
    """

    def buildTree(self, inorder, postorder):
        # write your code here
        return buildSubTree(inorder, 0, len(inorder), postorder, 0, len(postorder))


C++代码

/**
 * Definition of TreeNode:
 * class TreeNode {
 * public:
 *     int val;
 *     TreeNode *left, *right;
 *     TreeNode(int val) {
 *         this->val = val;
 *         this->left = this->right = NULL;
 *     }
 * }
 */
 

class Solution {
    /**
     *@param inorder : A list of integers that inorder traversal of a tree
     *@param postorder : A list of integers that postorder traversal of a tree
     *@return : Root of a tree
     */
public:
    TreeNode *buildTree(vector<int> &inorder, vector<int> &postorder) {
        // write your code here
        return buildSubTree(inorder.begin(),inorder.end(),postorder.begin(),postorder.end());
    }
    
    TreeNode *buildSubTree(vector<int>::iterator inBeg, vector<int>::iterator inEnd,
        vector<int>::iterator postBeg, vector<int>::iterator postEnd)
    {
        if(inBeg == inEnd || postBeg == postEnd)
        {
            return NULL;
        }//if
        
        TreeNode *root = new TreeNode(*(postEnd - 1));
        
        vector<int>::iterator pos = find(inBeg, inEnd, root->val);
        
        if(pos != inEnd)
        {
            int leftLen = pos - inBeg - 1;
            root->left = buildSubTree(inBeg,inBeg+leftLen+1, postBeg,postBeg+leftLen+1);
            root->right = buildSubTree(inBeg+leftLen+2,inEnd, postBeg+leftLen+1, postEnd -1 );
        }//if
        
        return root;
    }
};

GitHub -- C++源码


以上是关于LintCode(72)中序遍历和后序遍历树构造二叉树的主要内容,如果未能解决你的问题,请参考以下文章

根据中序遍历和后序遍历树构造二叉树

二叉树进阶题------前序遍历和中序遍历构造二叉树;中序遍历和后序遍历构造二叉树

二叉树进阶题------前序遍历和中序遍历构造二叉树;中序遍历和后序遍历构造二叉树

Java 构造二叉树如此简单

构造一棵二叉树,并分别输出其先序遍历、中序遍历和后序遍历的结果

中序和后序遍历构造二叉树