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

Construct Binary Tree from Inorder and Postorder Traversal

时间:2016-11-12 16:58:13      阅读:197      评论:0      收藏:0      [点我收藏+]

标签:color   strong   nod   log   pre   tor   二叉树   binary   public   

Construct Binary Tree from Inorder and Postorder Traversal

Given inorder and postorder traversal of a tree, construct the binary tree.

根据后序遍历和中序遍历构建一棵二叉树

/**
 * 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:
    void Build(int l1, int r1, int l2, int r2, const vector<int>& post, const vector<int> & in, TreeNode*& root){
        int i;
        for ( i = l2; i <= r2; i++)
        {
            if (in[i] == post[r1])
                break;
        }
        root = new TreeNode(post[r1]);
        if (i == l2)
            root->left = NULL;
        else
            Build(l1, l1 + i - l2 - 1, l2, i - 1,post, in,root->left); //边界条件
        if (i == r2)
            root->right = NULL;
        else
            Build(l1+i-l2, r1 - 1, i + 1, r2,post, in, root->right); //边界条件
        
    }
    TreeNode* buildTree(vector<int>& inorder, vector<int>& postorder) {
        if(postorder.size()==0 && inorder.size()==0)
            return nullptr;
        TreeNode* root;
        Build(0,postorder.size()-1, 0, inorder.size()-1, postorder, inorder, root);
        return root;
    }
};

 

Construct Binary Tree from Inorder and Postorder Traversal

标签:color   strong   nod   log   pre   tor   二叉树   binary   public   

原文地址:http://www.cnblogs.com/willwu/p/6056744.html

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