Construct Binary Tree from Inorder and Postorder Traversal

來源:互聯網
上載者:User

標籤:

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

Note:

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

題目解析:

用中序遍曆和後續遍曆還原二叉樹。並且二叉樹的節點的值沒有重複的。這樣就好做了,我們知道後序遍曆最後的節點是根節點,所以直接可以確定根節點,再在中序遍曆的數組中找值為根節點的下標index,這個下標之前的所有值都是左子樹的節點值得集合,求出集合的大小之後len,在後序遍曆中有數組開始的len個節點都是左子樹的。由此我們可以得到左子樹的中序遍曆以及後續遍曆的數組;同理,我們也可知道右子樹的中序遍曆以及後續遍曆的數組,這樣我們便可以用遞迴來實現。代碼如下:

/** * 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* BT(vector<int>&inorder,int instart,int inend,vector<int>&postorder,int pstart,int pend)    {        if(instart>inend) return NULL;        TreeNode* root=new TreeNode(postorder[pend]);        int index;        for(int i=instart;i<=inend;i++)        {            if(inorder[i]==root->val)            {                index=i;                break;            }        }        int len=index-instart;        TreeNode* left=BT(inorder,instart,index-1,postorder,pstart,pstart+len-1);        TreeNode* right=BT(inorder,index+1,inend,postorder,pstart+len,pend-1);        root->left=left;        root->right=right;        return root;    }    TreeNode* buildTree(vector<int>& inorder, vector<int>& postorder) {        if(inorder.size()==0) return NULL;        if(inorder.size()!=postorder.size()) return NULL;        TreeNode* node=BT(inorder,0,inorder.size()-1,postorder,0,postorder.size()-1);        return node;            }    };


著作權聲明:本文為博主原創文章,未經博主允許不得轉載。

Construct Binary Tree from Inorder and Postorder Traversal

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.