[leetcode]construct-binary-tree-from-inorder-and-postorder-traversal

题目描述

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

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

解法

  • 找到根节点,递归构造左子树和右子树
  • 使用std::find使得程序更简洁
  • 代码实现
/**
 * Definition for binary tree
 * 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.empty())
            return nullptr;
        
        auto rootItr = find(inorder.begin(), inorder.end(), postorder.back());
        vector<int> inLeft(inorder.begin(), rootItr);
        vector<int> inRight(rootItr + 1, inorder.end());
        vector<int> postLeft(postorder.begin(), postorder.begin() + inLeft.size());
        vector<int> postRight(postorder.begin() + inLeft.size(), postorder.end() - 1);
        
        TreeNode* cur = new TreeNode(postorder.back());
        cur -> left = buildTree(inLeft, postLeft);
        cur -> right = buildTree(inRight, postRight);
        
        return cur;
    }
};

猜你喜欢

转载自blog.csdn.net/zhwenx3/article/details/86940372