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计算出左子树的结点数。

  • 相关阅读:
    day_01 python基础 基本数据类型 if条件
    计算多边形周长和面积
    我研究出来的属性查询,贴自己的代码,请大家指教
    配置sde
    如何编辑SDE数据库(转载)
    ArcSED连接方式
    不同窗体传递数据
    sde stuff
    ArcSED
    不显示查询问题的解决(太完美了,新建一个图层,表示查询结果)
  • 原文地址:https://www.cnblogs.com/cff2121/p/10969276.html
Copyright © 2011-2022 走看看