zoukankan      html  css  js  c++  java
  • [面试真题] LeetCode:Construct Binary Tree from Preorder and Inorder Traversal

    Given preorder and inorder traversal of a tree, construct the binary tree.

    Note:You may assume that duplicates do not exist in the tree.

    解法:递归求解。

      基本情况:先序与中序数组长度小于1时,返回NULL。

      递归步骤:首先确定preorder的第一个元素一定是该树的root,再在inorder中找到该元素,标记为index,index左部为左子树的中序,右部为右子树的中序;随后通过左右子树中序的长度(可能为0),在preorder中确定左右子树的先序。

     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     TreeNode *buildTree(vector<int> &preorder,int ph, int pe, vector<int> &inorder, int ih, int ie){
    12         TreeNode *root;
    13         if(pe - ph < 0){
    14             return NULL;
    15         }
    16         root = new TreeNode(preorder[ph]);
    17         int index = ih-1;
    18         while(++index <= ie && inorder[index] != preorder[ph]){
    19         }
    20         int leftPreLen = index - ih;
    21         root->left = buildTree(preorder, ph+1, ph+leftPreLen, inorder, ih, index-1);
    22         root->right = buildTree(preorder, ph+leftPreLen+1, pe, inorder, index+1, ie);
    23         return root;
    24     }
    25     
    26 public:
    27     TreeNode *buildTree(vector<int> &preorder, vector<int> &inorder) {
    28         // Start typing your C/C++ solution below
    29         // DO NOT write int main() function
    30         return buildTree(preorder, 0, preorder.size()-1, inorder, 0, inorder.size()-1);
    31         
    32     }
    33 };

    Run Status: Accepted!
    Program Runtime: 164 milli secs

  • 相关阅读:
    工程师的十层楼,上
    工程师的十层楼 (下)
    2011CCTV中国经济年度人物评选结果揭晓
    IT行业程序员薪水差距之大的原因是什么
    单片机C应用开发班
    【分享】对输入子系统分析总结
    P6156 简单题 题解
    P3911 最小公倍数之和 题解
    dp 做题记录
    UVA12298 Super Poker II 题解
  • 原文地址:https://www.cnblogs.com/infinityu/p/3073908.html
Copyright © 2011-2022 走看看