zoukankan      html  css  js  c++  java
  • 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.

    /**
     * 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, int inorderStart,int inorderEnd,vector<int>& postorder,int postorderStart,int postorderEnd) {
            if(inorderEnd-inorderStart==1){
                return new TreeNode(inorder[inorderStart]);
            }
            if(inorderEnd-inorderStart==0){
                return 0;
            }
            int val = postorder[postorderEnd-1];
            int i=inorderStart;
            for(;i<inorderEnd;i++){
                if(inorder[i] == val){
                    break;
                }
            }
            TreeNode *root = new TreeNode(val);
            int leftLen = i-inorderStart;
            int rightLen = inorderEnd - i - 1;
            root->left = buildTree(inorder,inorderStart,inorderStart+leftLen,postorder,postorderStart,postorderStart+leftLen);
            root->right = buildTree(inorder,inorderStart+1+leftLen,inorderEnd,postorder,postorderStart+leftLen,postorderEnd-1);
            return root;
            
        }
        TreeNode* buildTree(vector<int>& inorder, vector<int>& postorder) {
            int postorederSize = postorder.size();
            int inorederSize = inorder.size();
            if(postorederSize != inorederSize){
                return NULL;
            }
            return buildTree(inorder,0,inorder.size(),postorder,0,postorder.size());
        }
    };
  • 相关阅读:
    台州 OJ 3847 Mowing the Lawn 线性DP 单调队列
    洛谷 OJ P1417 烹调方案 01背包
    快速幂取模
    台州 OJ 2649 More is better 并查集
    UVa 1640
    UVa 11971
    UVa 10900
    UVa 11346
    UVa 10288
    UVa 1639
  • 原文地址:https://www.cnblogs.com/zengzy/p/5008933.html
Copyright © 2011-2022 走看看