LeetCode——Construct Binary Tree from Inorder and Postorder Traversal

本文介绍了一种根据中序和后序遍历构建二叉树的方法。通过递归地找到根节点,并利用中序遍历确定左右子树的范围,从而完成整棵树的构建。文章包含详细的C++代码实现。

Question

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

Note:
You may assume that duplicates do not exist in the tree.

Solution

参考:http://www.cnblogs.com/zhonghuasong/p/7096300.html

Code

/**
 * 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) {
        if (inorder.size() == 0 || postorder.size() == 0)
            return NULL;
        return ConstructTree(inorder, postorder, 0, inorder.size() - 1, 0, postorder.size() - 1);
    }
    
    TreeNode* ConstructTree(vector<int>& inorder, vector<int>& postorder, 
            int in_start, int in_end, int post_start, int post_end) {
        int rootValue = postorder[post_end];
        TreeNode* root = new TreeNode(rootValue);
        
        if (in_start == in_end) {
            if (post_start == post_end && inorder[in_start] == postorder[post_start])
                return root;
        }
        
        int rootIn = in_start;
        while (rootIn <= in_end && inorder[rootIn] != rootValue)
            rootIn++;
        
        int leftPostLength = rootIn - in_start;
        if (leftPostLength > 0) {
            // 注意起点和终点的写法
            root->left = ConstructTree(inorder, postorder, in_start, rootIn - 1, post_start, post_start + leftPostLength - 1);
        }
        if (leftPostLength < in_end - in_start) {
            root->right = ConstructTree(inorder, postorder, rootIn + 1, in_end, post_start + leftPostLength, post_end - 1);
        }
        
        return root;
    }
};

转载于:https://www.cnblogs.com/zhonghuasong/p/7096358.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值