日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

LeetCode 106. 从中序与后序遍历序列构造二叉树(Construct Binary Tree from Inorder and Postorder Traversal)...

發布時間:2025/7/14 编程问答 31 豆豆
生活随笔 收集整理的這篇文章主要介紹了 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)...的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。