zoukankan      html  css  js  c++  java
  • 106. Construct Binary Tree from Inorder and Postorder Traversal (Tree; DFS)

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

    Note:
    You may assume that duplicates do not exist in the 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) {
            // Start typing your C/C++ solution below
            // DO NOT write int main() function
            root = NULL;
            if(inorder.empty()) return root;
            root = new TreeNode(0);
            buildSubTree(inorder,postorder,0,inorder.size()-1,0,postorder.size()-1,root);
            return root;
            
        }
        void buildSubTree(vector<int> &inorder, vector<int>&postorder, int inStartPos, int inEndPos, int postStartPos, int postEndPos,TreeNode * currentNode)
        {
            currentNode->val = postorder[postEndPos]; //后序遍历的最后一个节点是根节点
            
            //find root position in inorder vector
            int inRootPos;
            for(int i = inStartPos; i <= inEndPos; i++)
            {
                if(inorder[i] == postorder[postEndPos])
                {
                    inRootPos = i;
                    break;
                }
            }
            
            //right tree: 是中序遍历根节点之后的部分,对应后序遍历根节点前相同长度的部分
            int newPostPos = postEndPos - max(inEndPos - inRootPos, 0);
            if(inRootPos<inEndPos)
            {
                currentNode->right = new TreeNode(0);
                buildSubTree(inorder,postorder,inRootPos+1,inEndPos,newPostPos,postEndPos-1,currentNode->right);
            }
    
            //leftTree: 是中序遍历根节点之前的部分,对应后序遍历从头开始相同长度的部分
            if(inRootPos>inStartPos)
            {
                currentNode->left = new TreeNode(0);
                buildSubTree(inorder,postorder,inStartPos,inRootPos-1,postStartPos,newPostPos-1,currentNode->left);          
            }
        }
    private:
        TreeNode* root;
    };
  • 相关阅读:
    EJB>复合主键(Composite Primary Key)
    EJB>消息驱动beanTopic 消息的发送与接收(Pub/sub 消息传递模型)
    JSF>自订验证器
    EJB>自定义安全域
    EJB>Entity 的生命周期和状态、回调函数
    EJB>安全服务的具体开发
    单片机的中断系统
    JavaScript代码检查工具——JSLintMate
    如何开发一个 N9 上的程序
    NSIS安装制作基础教程
  • 原文地址:https://www.cnblogs.com/qionglouyuyu/p/4854531.html
Copyright © 2011-2022 走看看