LeetCode 106. 从中序与后序遍历序列构造二叉树(Construct Binary Tree from Inorder and Postorder Traversal)...
生活随笔
收集整理的這篇文章主要介紹了
LeetCode 106. 从中序与后序遍历序列构造二叉树(Construct Binary Tree from Inorder and Postorder Traversal)...
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
題目描述
?
根據一棵樹的中序遍歷與后序遍歷構造二叉樹。
注意:
你可以假設樹中沒有重復的元素。
例如,給出
中序遍歷 inorder =?[9,3,15,20,7] 后序遍歷 postorder = [9,15,7,20,3]返回如下的二叉樹:
3/ \9 20/ \15 7?
解題思路
?
利用回溯的思想,分別記錄生成樹時中序遍歷和后序遍歷對應的段首、段尾,每次構造樹時首先構造根節點為后序遍歷的尾節點,接著在中序遍歷序列中找到根的位置,然后根左對應左子樹,根右對應右子樹,對應到后序遍歷序列中分隔成兩段,遞歸構造左子樹和右子樹。
?
代碼
?
1 /** 2 * Definition for a binary tree node. 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 public: 12 TreeNode* buildTree(vector<int>& inorder, vector<int>& postorder) { 13 return build(inorder, postorder, 0, inorder.size() - 1, 0, postorder.size() - 1); 14 } 15 TreeNode* build(vector<int> inorder, vector<int> postorder, int iLeft, int iRight, int pLeft, int pRight){ 16 if(pLeft > pRight) return NULL; 17 TreeNode* root = new TreeNode(postorder[pRight]); 18 int idx = iLeft; 19 while(inorder[idx] != postorder[pRight]) idx++; 20 root->left = build(inorder, postorder, iLeft, idx - 1, pLeft, pLeft + idx - iLeft - 1); 21 root->right = build(inorder, postorder, idx + 1, iRight, pLeft + idx - iLeft, pRight - 1); 22 return root; 23 } 24 };?
轉載于:https://www.cnblogs.com/wmx24/p/9510338.html
總結
以上是生活随笔為你收集整理的LeetCode 106. 从中序与后序遍历序列构造二叉树(Construct Binary Tree from Inorder and Postorder Traversal)...的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: BZOJ3709: [PA2014]Bo
- 下一篇: MySql 安装