LeetCode-106-Construct Binary Tree from Inorder and Postorder Traversal
Posted 无名路人甲
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode-106-Construct Binary Tree from Inorder and Postorder Traversal相关的知识,希望对你有一定的参考价值。
算法描述:
Given inorder and postorder traversal of a tree, construct the binary tree.
Note:
You may assume that duplicates do not exist in the tree.
For example, given
inorder = [9,3,15,20,7] postorder = [9,15,7,20,3]
Return the following binary tree:
3 / 9 20 / 15 7
解题思路:理解原理,注意细节。
TreeNode* buildTree(vector<int>& inorder, vector<int>& postorder) { return helper(inorder, 0, inorder.size()-1, postorder, 0, postorder.size()-1); } TreeNode* helper(vector<int>& inorder, int is, int ie, vector<int>& postorder, int ps, int pe){ if(is > ie || ps > pe) return nullptr; TreeNode* node = new TreeNode(postorder[pe]); int pos = 0; for(int i=is; i <= ie; i++){ if(postorder[pe]==inorder[i]){ pos = i; break; } } node -> left = helper(inorder, is, pos-1, postorder, ps, ps - (is-pos+1)); node -> right = helper(inorder, pos+1, ie, postorder, ps - (is-pos+1)+1, pe-1); return node; }
以上是关于LeetCode-106-Construct Binary Tree from Inorder and Postorder Traversal的主要内容,如果未能解决你的问题,请参考以下文章
LeetCode-106-Construct Binary Tree from Inorder and Postorder Traversal
leetcode 106 Construct Binary Tree from Inorder and Postorder Traversal----- java
LeetCode106 Construct Binary Tree from Inorder and Postorder Traversal
[LeetCode] 106. Construct Binary Tree from Inorder and Postorder Traversal 由中序和后序遍历建立二叉树
LeetCode 106. Construct Binary Tree from Inorder and Postorder Traversal (用中序和后序树遍历来建立二叉树)
LeetCode106. Construct Binary Tree from Inorder and Postorder Traversal-通过中序和后续遍历还原二叉树