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

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > python >内容正文

python

二叉树 中序遍历 python_LeetCode 105 树 从前序与中序遍历序列构造二叉树(Medium)

發(fā)布時間:2025/3/8 python 22 豆豆
生活随笔 收集整理的這篇文章主要介紹了 二叉树 中序遍历 python_LeetCode 105 树 从前序与中序遍历序列构造二叉树(Medium) 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

17(105) 從前序與中序遍歷序列構(gòu)造二叉樹(Medium)

描述

根據(jù)一棵樹的前序遍歷與中序遍歷構(gòu)造二叉樹。

注意: 你可以假設(shè)樹中沒有重復的元素。

示例

例如,給出前序遍歷 preorder = [3,9,20,15,7] 中序遍歷 inorder = [9,3,15,20,7]返回如下的二叉樹:3/ 9 20/ 15 7

Description

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

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

Example

For example, givenpreorder = [3,9,20,15,7] inorder = [9,3,15,20,7] Return the following binary tree:3/ 9 20/ 15 7

BitDance Amazon Microsoft Adobe Apple Google Tencent Mi HuaWei VMware

解題

遞歸解法

class Solution { public:TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {if(preorder.empty()) return NULL;TreeNode* root=new TreeNode(preorder[0]);vector<int> preorder_left, inorder_left, preorder_right, inorder_right;int i;for(i=0;i<inorder.size();++i){if(inorder[i]==root->val) break;inorder_left.push_back(inorder[i]);}//中序遍歷根結(jié)點的左子樹存入inorder_leftfor(++i;i<inorder.size();++i){inorder_right.push_back(inorder[i]);}//中序遍歷根結(jié)點的右子樹存入inorder_rightfor(int j=1;j<preorder.size();++j){//根據(jù)中序遍歷左子樹的長度來確定前序遍歷左子樹存入preorder_leftif(j<=inorder_left.size()) preorder_left.push_back(preorder[j]);//前序遍歷剩下的為右子樹 存入前序遍歷右子樹序列preorder_rightelse preorder_right.push_back(preorder[j]);}root->left=buildTree(preorder_left,inorder_left);root->right=buildTree(preorder_right,inorder_right);return root;} };

總結(jié)

以上是生活随笔為你收集整理的二叉树 中序遍历 python_LeetCode 105 树 从前序与中序遍历序列构造二叉树(Medium)的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。