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.

    Solution:

    /**
     * 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 *built(vector<int> &inorder, vector<int> &postorder, int in_start, int in_end, int post_start, int post_end)
        {
            if(in_start > in_end || post_start > post_end) 
                return NULL;
            TreeNode *curRoot = new TreeNode(postorder[post_end]);
            int rootIndex = -1;
            for(int i = in_end;i >= in_start;i--)
            {
                if(inorder[i] == postorder[post_end])
                {
                    rootIndex = i;
                    break;
                }
            }
            if(rootIndex == -1) return NULL;
            int leftNum = rootIndex - in_start;
            curRoot -> left = built(inorder, postorder, in_start, rootIndex - 1, post_start, post_start + leftNum - 1);
            curRoot -> right = built(inorder, postorder, rootIndex + 1, in_end, post_start + leftNum, post_end - 1);
            return curRoot;
        }
    
        TreeNode *buildTree(vector<int> &inorder, vector<int> &postorder) {
            return built(inorder, postorder, 0, inorder.size() - 1, 0, postorder.size() - 1); 
        }
    };
  • 相关阅读:
    flask2 未整理
    flask1 未整理
    libvirt创建kvm虚拟机步骤
    libvirt之 virsh命令总结
    kvm的xml文件解释
    virsh命令和调用libvirt api的区别
    KVM
    libvirt
    kvm
    oracle中正则表达式的使用
  • 原文地址:https://www.cnblogs.com/changchengxiao/p/3619739.html
Copyright © 2011-2022 走看看