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

    遇到二叉树问题最先想到的是递归解决。

    使用 TreeNode * 引用,来保存暂时结果

    /**
     * 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) {
            TreeNode *root=NULL;
            if(inorder.empty()) return root;
            sub(root,inorder,0,inorder.size()-1,postorder,0,postorder.size()-1);
            return root;
            
        }
        void sub(TreeNode *&root,vector<int> &inorder,int istart,int iend,vector<int> &postorder,int pstart,int pend){
            if(istart>iend||pstart>pend){
                root=NULL;
                return;
            }
            root=new TreeNode(postorder[pend]);
            int split;
            for(int i=istart;i<=iend;i++){
                if(inorder[i]==postorder[pend]){
                    split=i;
                }
            }
            int leftnum=split-istart;  //表示左子树的节点个数
            TreeNode *l,*r;
            sub(l,inorder,istart,istart+leftnum-1,postorder,pstart,pstart+leftnum-1);
            sub(r,inorder,istart+leftnum+1,iend,postorder,pstart+leftnum,pend-1);
            root->left=l;
            root->right=r;
        }
    };


    版权声明:本文博主原创文章。博客,未经同意不得转载。

  • 相关阅读:
    Django -- 路由系统(URLconf)
    Django简介
    jQuery
    DOM
    JavaScript
    HTML,CSS
    Redis PK Memcached
    ORM框架-SQLAlchemy
    Memcached操作以及用法
    Py3快速下载地址
  • 原文地址:https://www.cnblogs.com/gcczhongduan/p/4853616.html
Copyright © 2011-2022 走看看