zoukankan      html  css  js  c++  java
  • Construct Binary Tree from Inorder and Postorder Traversal

    Construct Binary Tree from Inorder and Postorder Traversal

    Given inorder and postorder traversal of a tree, construct the binary 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:
        void Build(int l1, int r1, int l2, int r2, const vector<int>& post, const vector<int> & in, TreeNode*& root){
            int i;
            for ( i = l2; i <= r2; i++)
            {
                if (in[i] == post[r1])
                    break;
            }
            root = new TreeNode(post[r1]);
            if (i == l2)
                root->left = NULL;
            else
                Build(l1, l1 + i - l2 - 1, l2, i - 1,post, in,root->left); //边界条件
            if (i == r2)
                root->right = NULL;
            else
                Build(l1+i-l2, r1 - 1, i + 1, r2,post, in, root->right); //边界条件
            
        }
        TreeNode* buildTree(vector<int>& inorder, vector<int>& postorder) {
            if(postorder.size()==0 && inorder.size()==0)
                return nullptr;
            TreeNode* root;
            Build(0,postorder.size()-1, 0, inorder.size()-1, postorder, inorder, root);
            return root;
        }
    };
  • 相关阅读:
    elastic
    Leetcode题库 第十行
    Leetcode题库-实现strStr()
    Redis持久化
    Redis的数据结构及应用场景
    Redis缓存的淘汰策略
    Redis缓存常见问题
    Redis面试题1
    消息队列的原理及选型
    【转载】java高并发/mysql/mybatis/spring博客
  • 原文地址:https://www.cnblogs.com/willwu/p/6056744.html
Copyright © 2011-2022 走看看