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

    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.

    地址:https://oj.leetcode.com/problems/construct-binary-tree-from-inorder-and-postorder-traversal/

    算法:根据中序和后序构造出二叉树。细心一点应该不会错。代码:

     1 /**
     2  * Definition for binary tree
     3  * struct TreeNode {
     4  *     int val;
     5  *     TreeNode *left;
     6  *     TreeNode *right;
     7  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
     8  * };
     9  */
    10 class Solution {
    11 public:
    12     TreeNode *buildTree(vector<int> &inorder, vector<int> &postorder) {
    13         if(inorder.empty()) return NULL;
    14         return subBuildTree(inorder,postorder,0,inorder.size()-1,0,postorder.size()-1);
    15     }
    16     TreeNode *subBuildTree(vector<int> &inorder, vector<int> &postorder, int inbegin, int inend, int postbegin, int postend){
    17         TreeNode *root = new TreeNode(postorder[postend]);
    18         if(inbegin == inend && postbegin == postend){
    19             return root;
    20         }
    21         int key = postorder[postend];
    22         int i = inbegin;
    23         while(i <= inend && inorder[i] != key)  ++i;
    24         if(i > inbegin){
    25             root->left = subBuildTree(inorder,postorder,inbegin,i-1,postbegin,postbegin+i-1-inbegin);
    26         }
    27         if(inend > i){
    28             root->right = subBuildTree(inorder,postorder,i+1,inend,postbegin+i-inbegin,postend-1);
    29         }
    30         return root;
    31     }
    32 };
  • 相关阅读:
    学习CSS定位(布局)
    XSLT
    CSS模型框学习笔记
    XMLDOM复习
    XMLDOM之浏览器差异
    HTMLDOM入门
    学习二级纵向菜单两步走
    Xpath很全的学习地点,不看后悔
    LinQ To XML
    收集的一些零散代码
  • 原文地址:https://www.cnblogs.com/boostable/p/leetcode_construct_binary_tree_from_inorder_and_postorder_traversal.html
Copyright © 2011-2022 走看看