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

    For example, given

    inorder = [9,3,15,20,7]
    postorder = [9,15,7,20,3]

    Return the following binary tree:

        3
       / 
      9  20
        /  
       15   7

    题目给出二叉数的中序和后序遍历,要求写出二叉树的具体形式。
    后序遍历的遍历数序为左子树->右子树->根结点,因此最后一个结点就是二叉树的根结点,
    由根结点可将中序遍历分成左子树和右子树,再根据左子树的结点数,将后序遍历中的左子树和右子树分开。
    再对左子树和右子树进行相同的操作。

    代码如下:
    class Solution {
    public:
        TreeNode* buildTree(vector<int>& inorder, vector<int>& postorder) {
            return build(inorder,0,inorder.size()-1,postorder,0,postorder.size()-1);
        }
        TreeNode* build(vector<int>& inorder,int iLeft,int iRight, vector<int>& postorder,int pLeft,int pRight){
            if(iLeft>iRight || pLeft>pRight)return NULL;
            
            TreeNode* root=new TreeNode(postorder[pRight]);;
            int i=iLeft;
            while(i<=iRight){
                if(inorder[i]==postorder[pRight]){
                    break;
                }
                ++i;
            }
            
            root->left=build(inorder,iLeft,i-1,postorder,pLeft,pLeft+i-iLeft-1);
            root->right=build(inorder,i+1,iRight,postorder,pLeft+i-iLeft,pRight-1);
            
            return root;
        }
    };

    i-iLeft计算出左子树的结点数。

  • 相关阅读:
    remove all event handlers from a control
    clone Control event handlers at run time
    EventHandlerList z
    code
    From delegates to lambdas z
    tpl Dataflow for net 4.0
    FlowLayoutPanel autowrapping doesn't work with autosize
    easyui radio 取值和赋值
    jquery hide和show方法
    java设计模式 工厂模式
  • 原文地址:https://www.cnblogs.com/cff2121/p/10969276.html
Copyright © 2011-2022 走看看