Leetcode 105. 从前序与中序遍历序列构造二叉树 解题思路及C++实现
生活随笔
收集整理的這篇文章主要介紹了
Leetcode 105. 从前序与中序遍历序列构造二叉树 解题思路及C++实现
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
解題思路:
前序遍歷preorder中,第一個(gè)即為根節(jié)點(diǎn),然后找到中序遍歷inorder中對(duì)應(yīng)的節(jié)點(diǎn),則inorder中該節(jié)點(diǎn)之前的值均在根節(jié)點(diǎn)的左子樹(shù)上,該節(jié)點(diǎn)后面的值都在根節(jié)點(diǎn)的右子樹(shù)上,所以可以使用遞歸構(gòu)建二叉樹(shù),分別對(duì)其左子樹(shù)的節(jié)點(diǎn)、右子樹(shù)的節(jié)點(diǎn)構(gòu)建數(shù)。
?
/*** 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>& preorder, vector<int>& inorder) {return conTree(preorder, 0, preorder.size()-1, inorder, 0, inorder.size()-1);}TreeNode* conTree(vector<int>& preorder, int pl, int pr, vector<int>& inorder, int il, int ir){if(pl > pr || il > ir)return NULL;TreeNode* root = new TreeNode(preorder[pl]);for(int i = il; i <= ir; i++){if(preorder[pl] == inorder[i]){root->left = conTree(preorder, pl+1, pl+i-il, inorder, il, i-1);root->right = conTree(preorder, pl+i-il+1, pr, inorder, i+1, ir);break;}}return root;} };?
?
總結(jié)
以上是生活随笔為你收集整理的Leetcode 105. 从前序与中序遍历序列构造二叉树 解题思路及C++实现的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: Leetcode 102. 二叉树的层次
- 下一篇: Leetcode 106. 从中序与后序