[leetcode] 105. Construct Binary Tree from Preorder and Inorder Traversal

网友投稿 806 2022-08-23

[leetcode] 105. Construct Binary Tree from preorder and inorder Traversal

[leetcode] 105. Construct Binary Tree from Preorder and Inorder Traversal

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.

For example, given

preorder = [3,9,20,15,7]inorder = [9,3,15,20,7]

Return the following binary tree:

3 / \ 9 20 / \ 15 7

分析

题目的意思是:利用前序遍历和中序遍历来重构二叉数。

前序遍历是中左右,中序遍历是左中右,前序遍历可以找到根结点,中序遍历可以根据根结点确定左右分支,然后递归。但是在递归的时候分左右分支索引的时候遇见了点麻烦,之后改变利用count计数找到左右分支,方便了很多。这种题的解法很固定,所以有必要记忆一下。

代码

/** * 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& preorder, vector& inorder) { return buildTree(preorder,inorder,0,preorder.size()-1,0,inorder.size()-1); } TreeNode* buildTree(vector& preorder, vector& inorder,int pLeft,int pRight,int iLeft,int iRight){ if(pLeft>pRight||iLeft>iRight){ return NULL; } int count=0; for(int i=iLeft;i<=iRight;i++){ if(preorder[pLeft]==inorder[i]){ break; } count++; } TreeNode* root=new TreeNode(preorder[pLeft]); root->left=buildTree(preorder,inorder,pLeft+1,pLeft+count,iLeft,iLeft+count-1); root->right=buildTree(preorder,inorder,pLeft+1+count,pRight,iLeft+count+1,iRight); return root; }};

参考文献

​​[编程题]construct-binary-tree-from-preorder-and-inorder-traversal​​​​[LeetCode] Construct Binary Tree from Preorder and Inorder Traversal 由先序和中序遍历建立二叉树​​

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:Android Studio 小技巧汇总(android studio模拟器运行不了)
下一篇:[leetcode] 523. Continuous Subarray Sum
相关文章

 发表评论

暂时没有评论,来抢沙发吧~