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

歡迎訪問 生活随笔!

生活随笔

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

编程问答

【Construct Binary Tree from Inorder and Postorder Traversal】cpp

發布時間:2023/12/19 编程问答 33 豆豆
生活随笔 收集整理的這篇文章主要介紹了 【Construct Binary Tree from Inorder and Postorder Traversal】cpp 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

題目:

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

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

代碼:

/*** 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* buildTree(vector<int>& inorder, vector<int>& postorder) {if ( inorder.size()==0 || postorder.size()==0 ) return NULL;return Solution::buildTreeIP(inorder, 0, inorder.size()-1, postorder, 0, postorder.size()-1);}static TreeNode* buildTreeIP(vector<int>& inorder, int bI, int eI, vector<int>& postorder, int bP, int eP ){if ( bI > eI ) return NULL;TreeNode *root = new TreeNode(postorder[eP]);int rootPosInorder = bI;for ( int i = bI; i <= eI; ++i ){if ( inorder[i]==root->val ) { rootPosInorder=i; break; }}int leftSize = rootPosInorder - bI;int rightSize = eI - rootPosInorder;root->left = Solution::buildTreeIP(inorder, bI, rootPosInorder-1, postorder, bP, bP+leftSize-1);root->right = Solution::buildTreeIP(inorder, rootPosInorder+1, eI, postorder, eP-rightSize, eP-1);return root;} };

tips:

思路跟Preorder & Inorder一樣。

這里要注意:

1. 算左子樹和右子樹長度時,要在inorder里面算

2. 左子樹和右子樹長度可能一樣,也可能不一樣;因此在計算root->left和root->right的時候,要注意如何切vector下標(之前一直當成左右樹長度一樣,debug了一段時間才AC)

==============================================

第二次過這道題,沿用了之前construct binary tree的思路,代碼一次AC。

/*** 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* buildTree(vector<int>& inorder, vector<int>& postorder){return Solution::build(inorder, 0, inorder.size()-1, postorder, 0, postorder.size()-1);}TreeNode* build(vector<int>& inorder, int bi, int ei,vector<int>& postorder, int bp, int ep){if ( bi>ei || bp>ep) return NULL;TreeNode* root = new TreeNode(postorder[ep]);int right_range = ei - Solution::findPos(inorder, bi, ei, postorder[ep]);int left_range = ei - bi - right_range;root->left = Solution::build(inorder, bi, ei-right_range-1, postorder, bp, ep-right_range-1);root->right = Solution::build(inorder, bi+left_range+1 , ei, postorder, bp+left_range, ep-1);return root;}int findPos(vector<int>& order, int begin, int end, int val){for ( int i=begin; i<=end; ++i ) if (order[i]==val) return i;} };

?

轉載于:https://www.cnblogs.com/xbf9xbf/p/4507596.html

總結

以上是生活随笔為你收集整理的【Construct Binary Tree from Inorder and Postorder Traversal】cpp的全部內容,希望文章能夠幫你解決所遇到的問題。

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