CoolSummer

数据可视化&AI

Construct Binary Tree from Inorder and Postorder Traversal

一、问题描述

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

二、思路

Construct Binary Tree from Preorder and Inorder Traversal思路基本一致,主要是根据在中序遍历中找到当前的值,然后通过对应关系递归。

三、代码

/**
 * 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) {
        return creatTree(0, inorder.size() - 1, 0, postorder.size() - 1, inorder, postorder);
    }
    TreeNode*creatTree(int in_begin, int in_end, int post_begin,int post_end, vector<int> &inorder, vector<int> &postorder){
        if(post_begin > post_end)    return NULL;
        TreeNode* root = new TreeNode(postorder[post_end]);
        int index = 0;
        for(int i = in_end; i >= 0; --i){
            if(inorder[i] == root -> val){
                index = i;
                break;
            }
        }
        root -> right = creatTree(index + 1, in_end, post_begin + index - in_begin, post_end - 1, inorder, postorder);
        root -> left = creatTree(in_begin, index - 1, post_begin, post_begin + index - in_begin - 1, inorder, postorder);
        return root;
    }
};


阅读更多
版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u014744118/article/details/52384095
文章标签: C++ leetcode
个人分类: LeetCode
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

不良信息举报

Construct Binary Tree from Inorder and Postorder Traversal

最多只允许输入30个字

加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!
关闭
关闭