LeetCode-106.Construct Binary Tree from Inorder and Postorder Traversal
2016-06-26 22:03
369 查看
https://leetcode.com/problems/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.
递归版
测试用例
inorder:[4,7,2,1,5,3,8,6]
postorder:[7,4,2,5,8,6,3,1]
结果:
[1,2,3,4,null,5,6,null,7,null,null,8]
Given inorder and postorder traversal of a tree, construct the binary tree.
Note:
You may assume that duplicates do not exist in the tree.
递归版
/** * 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* helper(vector<int> &in, int inLow, int inHigh, vector<int> &post, int postLow, int postHigh) { if (inLow > inHigh) return NULL; TreeNode* root = new TreeNode(post[postHigh]); int rootIndex = 0; for (int i = inLow; i <= inHigh; i++) { if (in[i] == post[postHigh]) { rootIndex = i; break; } } root->left = helper(in, inLow, rootIndex - 1, post, postLow, rootIndex - 1 - inLow + postLow); root->right = helper(in, rootIndex + 1, inHigh, post, postHigh - inHigh + rootIndex, postHigh - 1); return root; } TreeNode* buildTree(vector<int>& inorder, vector<int>& postorder) { return helper(inorder,0, inorder.size()-1, postorder, 0, postorder.size()-1); } };
测试用例
inorder:[4,7,2,1,5,3,8,6]
postorder:[7,4,2,5,8,6,3,1]
结果:
[1,2,3,4,null,5,6,null,7,null,null,8]
相关文章推荐
- leetcode 179 Largest Number
- leetcode 24 Swap Nodes in Pairs
- leetcode 2 Add Two Numbers 方法1
- leetcode 2 Add Two Numbers 方法2
- leetcode----Longest Substring Without Repeating Characters
- [LeetCode]47 Permutations II
- [LeetCode]65 Valid Number
- [LeetCode]123 Best Time to Buy and Sell Stock III
- [LeetCode] String Reorder Distance Apart
- [LeetCode] Sliding Window Maximum
- [LeetCode] Find the k-th Smallest Element in the Union of Two Sorted Arrays
- [LeetCode] Determine If Two Rectangles Overlap
- [LeetCode] A Distance Maximizing Problem
- leetcode_linearList
- leetcode_linearList02
- 021-Merge Two Sorted Lists(合并两个排好序的单链表);leetcode
- LeetCode[Day 1] Two Sum 题解
- LeetCode[Day 2] Median of Two Sorted Arrays 题解
- LeetCode[Day 3] Longest Substring Without... 题解
- LeetCode [Day 4] Add Two Numbers 题解