LintCode-72.中序遍历和后序遍历树构造二叉树

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

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

注意事项

你可以假设树中不存在相同数值的节点

样例

给出树的中序遍历: [1,2,3] 和后序遍历: [1,3,2]
返回如下的树:
  2
 /   1   3

标签

二叉树

code
/**
 * 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
        TreeNode *root = NULL;
        vector<int> inorder_l,inorder_r,postorder_l,postorder_r;
        int i,root_index=0;
        int size = postorder.size();

        if(inorder.empty()!=1 || postorder.empty()!=1) {
            root = new TreeNode(postorder[size-1]); //  在后序队列中找根节点

            //  在中序队列中找出根节点位置
            for(i=0; i<inorder.size(); i++) {
                if(postorder[size-1] == inorder[i])
                    break;
                root_index++;
            }

            //  左右子树的前序、中序队列
            for(i=0; i<root_index; i++) {
                postorder_l.push_back(postorder[i]);
                inorder_l.push_back(inorder[i]);
            }
            for(i=root_index+1; i<inorder.size(); i++) {
                postorder_r.push_back(postorder[i-1]);
                inorder_r.push_back(inorder[i]);
            }

            root->left = buildTree(inorder_l, postorder_l);
            root->right = buildTree(inorder_r, postorder_r);
        }
        return root;
    }
};

转载于:https://www.cnblogs.com/libaoquan/p/6806626.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值