zoukankan      html  css  js  c++  java
  • leetcode 刷题之路 64 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.

    给出二叉树的中序遍历和后序遍历结果,恢复出二叉树。

    后序遍历序列的最后一个元素值是二叉树的根节点的值。查找该元素在中序遍历序列中的位置mid,依据中序遍历和后序遍历性质。有:

    位置mid曾经的序列部分为二叉树根节点左子树中序遍历的结果,得出该序列的长度n,则后序遍历序列前n个元素为二叉树根节点左子树后序遍历的结果。由这两个中序遍历和后序遍历子序列恢复出左子树。

    位置mid以后的序列部分为二叉树根节点右子树中序遍历的结果,得出该序列的长度m,则后序遍历序列(除去最后一个元素)后m个元素为二叉树根节点右子树后序遍历的结果,由这两个中序遍历和后序遍历子序列恢复出左子树;

    以上描写叙述中递归地引用了由中序遍历和后序遍历恢复子树的部分,因此程序也採用递归实现。

    AC code:

    /**
     * Definition for binary tree
     * struct TreeNode {
     *     int val;
     *     TreeNode *left;
     *     TreeNode *right;
     *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
     * };
     */
     
    
     TreeNode *helper(vector<int> &inorder, int b1, int e1, vector<int> &postorder, int b2, int e2)
     {
    	 if (b1>e1)
    		 return NULL;
    	 int mid;
    	 for (int i = b1; i <= e1; i++)
    		 if (inorder[i] == postorder[e2])
    		 {
    			 mid = i;
    			 break;
    		 }
    			 
    
    	 TreeNode* root = new TreeNode(inorder[mid]);
    	 root->left = helper(inorder, b1, mid - 1, postorder, b2, b2 + mid - b1-1);
    	 root->right = helper(inorder, mid + 1, e1, postorder, b2 + mid-b1, e2 - 1);
    	 return root;
     }
     class Solution {
     public:
    	 TreeNode *buildTree(vector<int> &inorder, vector<int> &postorder)
    	 {
    		 return helper(inorder, 0, inorder.size() - 1, postorder, 0, postorder.size() - 1);
    	 }
     };





  • 相关阅读:
    crawler_URL编码原理详解
    linux_常用压缩,解压缩命令
    myql_链接丢失异常_mybaits _等框架_报错_The last packet successfully
    linux_shell_类似sql的orderby 取最大值
    php_cawler_html嵌套标签清洗
    vim_编码配置文件_utf8乱码解决
    python_random随机
    linux_shell_轮询触发启动脚本
    crawler_http关闭连接
    linux_mac_配置itrem2 rz sz_bug处理
  • 原文地址:https://www.cnblogs.com/mfrbuaa/p/5207473.html
Copyright © 2011-2022 走看看