• 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.

    思路:从中序遍历和后序遍历的数组中找到唯一的二叉树。首先找到根结点,后序遍历最末位是根结点,然后找出中序遍历根结点的位置,记录index,且计算左子树的长度。递归方法,在左子树和右子树的遍历数组中再找出左子树和右子树的根结点,以此类推。

    /**
     * Definition for binary tree
     * struct TreeNode {
     *     int val;
     *     TreeNode *left;
     *     TreeNode *right;
     *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
     * };
     */
    class Solution {
    public:
        void buildBST(TreeNode *&root,vector<int> &inorder,int inBegin,int inEnd,vector<int> &postorder,int postBegin,int postEnd)
        {
            if(inBegin>inEnd || postBegin>postEnd)
                return;
            int pRoot=postorder[postEnd];
            root=new TreeNode(pRoot);
            int index=0;
            for(int i=0;i<=inEnd;i++)
            {
                if(pRoot==inorder[i])
                {
                    index=i;
                    break;
                }
            }
            int in_len=index-inBegin;
            buildBST(root->left,inorder,inBegin,index-1,postorder,postBegin,postBegin+in_len-1);
            buildBST(root->right,inorder,index+1,inEnd,postorder,postBegin+in_len,postEnd-1);
        }
        TreeNode *buildTree(vector<int> &inorder, vector<int> &postorder) {
            TreeNode *root;
            if(inorder.empty() || postorder.empty())
                return NULL;
            int inEnd=inorder.size()-1;
            int postEnd=postorder.size()-1;
            buildBST(root,inorder,0,inEnd,postorder,0,postEnd);
            return root;
        }
    };
  • 相关阅读:
    异构数据库同步工具调研
    ubuntu16.04 Golang语言开发环境搭建
    串口USB单一映射及重命名
    linux arm 交叉编译ACE(ubuntu16.04)
    ubuntu16.04 下Mongo数据库搭建
    ubuntu 增加一个用户 并赋予权限
    go 通过http发送图片file内容
    git 简单命令总结
    gitlab ssh_key
    ubuntu16.04 程序开机自启动设置及启动优化
  • 原文地址:https://www.cnblogs.com/awy-blog/p/3691943.html
Copyright © 2020-2023  润新知