LeetCode106 Construct Binary Tree from Inorder and Postorder Traversal
Posted wangxiaobao的博客
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode106 Construct Binary Tree from Inorder and Postorder Traversal相关的知识,希望对你有一定的参考价值。
Given inorder and postorder traversal of a tree, construct the binary tree. (Medium)
Note:
You may assume that duplicates do not exist in the tree.
分析:
跟前一题方法一样,只需要分析出中序与后序恢复时,需从后序的最后一个元素读出来当做根节点,在中序中寻找其位置。
其余递归过程跟前序中序恢复一致。
代码:
1 /** 2 * Definition for a binary tree node. 3 * struct TreeNode { 4 * int val; 5 * TreeNode *left; 6 * TreeNode *right; 7 * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 * }; 9 */ 10 class Solution { 11 private: 12 TreeNode* helper(vector<int>& inorder, int inStart, int inEnd, vector<int>& postorder, int postStart, int postEnd) { 13 int sz = inEnd - inStart; 14 if (sz == 0) { 15 return nullptr; 16 } 17 int rootVal = postorder[postEnd - 1]; 18 TreeNode* root = new TreeNode(rootVal); 19 int pos; 20 for (pos = 0; pos < sz; ++pos) { 21 if (inorder[inStart + pos] == rootVal) { 22 break; 23 } 24 } 25 if (pos < 0) { 26 root -> left = nullptr; 27 } 28 else { 29 root -> left = helper(inorder, inStart , inStart + pos, postorder, postStart, postStart + pos); 30 } 31 if (pos + 1 >= sz) { 32 root -> right = nullptr; 33 } 34 else { 35 root -> right = helper(inorder, inStart + pos + 1, inEnd, postorder, postStart + pos, postEnd - 1); 36 } 37 return root; 38 } 39 public: 40 TreeNode* buildTree(vector<int>& inorder, vector<int>& postorder) { 41 return helper(inorder, 0, inorder.size(), postorder, 0, postorder.size()); 42 } 43 };
以上是关于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
leetcode 106 Construct Binary Tree from Inorder and Postorder Traversal----- java
LeetCode106 Construct Binary Tree from Inorder and Postorder Traversal
LeetCode-面试算法经典-Java实现106-Construct Binary Tree from Inorder and Postorder Traversal(构造二叉树II)(示例(代码片
[LeetCode] 106. Construct Binary Tree from Inorder and Postorder Traversal 由中序和后序遍历建立二叉树