码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2016-06-16 15:05:06      阅读:190      评论:0      收藏:0      [点我收藏+]

标签:

题目

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

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

样例

给出树的中序遍历: [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)中序遍历和后序遍历树构造二叉树

标签:

原文地址:http://blog.csdn.net/fly_yr/article/details/51685182

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!