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, vector<int>& postorder) {
            int posStart=0,preEnd=postorder.size()-1;
            int inStart=0,inEnd=inorder.size()-1;
            
            return constructHelper(postorder,posStart,preEnd,
                    inorder, inStart, inEnd);
        }
        
        TreeNode* constructHelper(vector<int>&postorder,int posStart,int posEnd,
                    vector<int>&inorder,int inStart,int inEnd){
            if(posStart>posEnd||inStart>inEnd)  return NULL;
            
            int val=postorder[posEnd];
            TreeNode*p =new TreeNode(val);
            int k=0;
            for(int i=0;i<inorder.size();i++){
                if(inorder[i]==val){
                    k=i;break;//第k个
                } 
            }
            
            p->left= constructHelper(postorder,posStart,posStart+k-inStart-1,inorder, inStart,k-1);//k之前
                    //k-start  考虑这种情况,在找到右子树的左子树的时候
                    //k在右边,inStart也在右边,此时需要找的是左边的个数,
                    //k-inStart 就解决了这个问题
            p->right=constructHelper(postorder,posStart+k-inStart , posEnd-1,inorder,k+1, inEnd); 
            return p;        
        }
    };


  • 相关阅读:
    itoa
    sprintf用法 [转载]
    atoi 与 itoa的实现
    数组排序总结(冒泡,选择,插入,希尔)
    XML入门精解之文件格式定义(DTD)
    malloc()函数的工作机制 结构体的总结
    字符串指针与字符数组(ZT)
    sprintf函数你了解有多深!
    sprintf
    sql ldr 笔记
  • 原文地址:https://www.cnblogs.com/jsrgfjz/p/8519838.html
Copyright © 2011-2022 走看看