zoukankan      html  css  js  c++  java
  • 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.

    思路:



    如果所示的二叉树,前序遍历: 4 1 3 2 7 6 5 

        后序遍历: 3 1 2 4 6 7 5


    前序遍历中开始存放的是根节点,所以第一个就是根节点。然后再中序遍历中寻找那个根节点,找到其索引值,然后我们发现从一开始到这个索引值对应的数值,也就是这个根节点,这一部分全部是左边的节点,有半部分全部是右边的节点。

    如此递归即可。

    代码:

    /**
     * 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:
        TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {
            int preStart=0,preEnd=preorder.size()-1;
            int inStart=0,inEnd=inorder.size()-1;
            
            return constructHelper(preorder,preStart,preEnd,
                    inorder, inStart,inEnd);
        }
        
        TreeNode* constructHelper(vector<int>&preorder,int preStart,int preEnd,
                    vector<int>&inorder,int inStart,int inEnd){
            if(preStart>preEnd||inStart>inEnd)  return NULL;
            
            int val=preorder[preStart];
            TreeNode*p =new TreeNode(val);
            int k=0;
            for(int i=0;i<inorder.size();i++){
                if(inorder[i]==val){
                    k=i;break;
                } 
            }
            
            p->left= constructHelper(preorder,preStart+1,preStart+(k-inStart),
                    inorder, inStart,k-1);//k之前
                    //k-start  考虑这种情况,在找到右子树的左子树的时候
                    //k在右边,inStart也在右边,此时需要找的是左边的个数,
                    //k-inStart 就解决了这个问题
            p->right=constructHelper(preorder,preStart+(k-inStart)+1, preEnd,
                    inorder,k+1, inEnd); 
            return p;        
        } 
    };


  • 相关阅读:
    【学习笔记】整除分块
    【Luogu P2201】【JZOJ 3922】数列编辑器
    【SSL1786】麻将游戏
    【SSL2325】最小转弯问题
    【JZOJ 3910】Idiot 的间谍网络
    【Luogu P1879】[USACO06NOV]玉米田Corn Fields
    【JZOJ 3909】Idiot 的乘幂
    【JZOJ 3918】蛋糕
    【Luogu P3174 】[HAOI2009]毛毛虫
    【SSL1194】最优乘车
  • 原文地址:https://www.cnblogs.com/jsrgfjz/p/8519839.html
Copyright © 2011-2022 走看看