LeetCode 106. 已知中序和后序遍历构建二叉树

LeetCode 106. 已知中序和后序遍历构建二叉树

题目

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

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

思考

举个例子,如下图中的二叉树:
二叉树
中序遍历为:21435
后序遍历为:24531

还原树的方法:
1. 后序遍历中最后一个为树(或子树)的根,即为1;
2. 用根将中序遍历分为左子树的中序遍历(2)和右子树的中序遍历(435);
3. 按照中序遍历得到左右子树的元素后将后序遍历也分为左子树的后序遍历(2)和右子树的后序遍历(453);
4. 对于左右子树的中序遍历和后序遍历分别进行第一步操作,直到得到结果的二叉树。

我的答案

根据递归的思想得出:
c++

/**
 * 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) {
            return NULL;
        }
        int rootNum = postorder.back();
        TreeNode* root = new TreeNode(rootNum);
        if (inorder.size() == 1) {
            return root;
        }
        bool left1 = true;
        vector<int>* inorderLeft = new vector<int>;
        vector<int>* inorderRight = new vector<int>;
        vector<int>* postorderLeft = new vector<int>;
        vector<int>* postorderRight = new vector<int>;
        for (int i = 0; i < inorder.size(); i++) {
            if (inorder[i] == rootNum) {
                left1 = false;
            } else if (left1) {
                inorderLeft->push_back(inorder[i]);
                postorderLeft->push_back(postorder[i]);
            } else {
                inorderRight->push_back(inorder[i]);
                postorderRight->push_back(postorder[i - 1]);
            }
        }
        // 释放内存
        vector<int>().swap(inorder);
        vector<int>().swap(postorder);
        root->left = buildTree(*inorderLeft, *postorderLeft);
        root->right = buildTree(*inorderRight, *postorderRight);
        return root;
    }
};

上述方法效率较低,应该避免new新的vector,可以用传下标参数(用find函数找出根元素位置)来实现。

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值