您的位置:首页
leetcode: Construct Binary Tree from Inorder and Postorder Traversal
2017-08-21 10:06
423 查看
/** * Definition for binary tree * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: TreeNode *buildTree(vector<int> &inorder, vector<int> &postorder) { if( inorder.size() != postorder.size()) return NULL; return core( inorder, 0, inorder.size()-1, postorder, 0, postorder.size()-1); } TreeNode *core( vector< int> &inorder, int left, int right, vector< int> &postorder, int start, int end){ if( left > right || start > end) return NULL; TreeNode *root = new TreeNode( postorder[end]); int i = left; for( ; i <= right; ++i){ if( inorder[i] == postorder[end]) break; } root->left = core( inorder, left, i-1, postorder, start, start+(i-left)-1);//这里要用下标减left,算offset。不然会数组越界 root->right = core( inorder, i+1, right, postorder, start+(i-left), end-1);//这里要用下标减left。算offset,不然会数组越界 return root; } };
相关文章推荐
- [Leetcode] Construct Binary Tree from Inorder and Postorder Traversal
- LeetCode106—Construct Binary Tree from Inorder and Postorder Traversal
- 【LeetCode】Construct Binary Tree from Inorder and Postorder Traversal
- [leetcode] 106. Construct Binary Tree from Inorder and Postorder Traversal 解题报告
- LeetCode-Construct Binary Tree from Inorder and Postorder Traversal
- leetcode106. Construct Binary Tree from Inorder and Postorder Traversal
- 【LeetCode】106. Construct Binary Tree from Inorder and Postorder Traversal
- [LeetCode] Construct Binary Tree from Inorder and Postorder Traversal
- leetcode - Construct Binary Tree from Inorder and Postorder Traversal
- LeetCode:Construct Binary Tree from Inorder and Postorder Traversal
- Leetcode Construct Binary Tree from Inorder and Postorder Traversal
- LeetCode 106. Construct Binary Tree from Inorder and Postorder Traversal(根据中序遍历和后序遍历构造二叉树)
- [LeetCode]Construct Binary Tree from Inorder and Postorder Traversal
- LeetCode Construct Binary Tree from Inorder and Postorder Traversal
- Leetcode145: Construct Binary Tree from Inorder and Postorder Traversal
- leetCode(18):Construct Binary Tree from Preorder and Inorder (Inorder and Postorder) Traversal 分类: leetCode 2015-06-22 08:26 177人阅读 评论(0) 收藏
- LeetCode——Construct Binary Tree from Inorder and Postorder Traversal
- [leetcode]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