【Leetcode】Construct binary tree from inorder and postorder traversal
2015-09-03 03:10
519 查看
【题目】
Given inorder and postorder traversal of a tree, construct the binary tree.
Note:
You may assume that duplicates do not exist in the tree.
【思路】
pretty similar with that of
【代码】
public TreeNode buildTree(int[] inorder, int[] postorder) {
if(inorder.length == 0 || inorder.length != postorder.length) return null;
return buildTree(inorder,postorder,0,inorder.length-1,0,postorder.length-1);
}
public TreeNode buildTree(int[] inorder, int[]postorder, int ilow, int ihigh, int plow, int phigh) {
TreeNode root = new TreeNode(postorder[phigh]);
int i=-1;
for(i = ilow; i <= ihigh; i++) {
if(root.val == inorder[i]) {
break;
}
}
if(i != ilow) root.left = buildTree(inorder, postorder, ilow, i-1, plow,plow+i-ilow-1);
if(i != ihigh) root.right = buildTree(inorder,postorder, i+1, ihigh, plow+i-ilow, phigh-1);
return root;
}
Given inorder and postorder traversal of a tree, construct the binary tree.
Note:
You may assume that duplicates do not exist in the tree.
【思路】
pretty similar with that of
【代码】
public TreeNode buildTree(int[] inorder, int[] postorder) {
if(inorder.length == 0 || inorder.length != postorder.length) return null;
return buildTree(inorder,postorder,0,inorder.length-1,0,postorder.length-1);
}
public TreeNode buildTree(int[] inorder, int[]postorder, int ilow, int ihigh, int plow, int phigh) {
TreeNode root = new TreeNode(postorder[phigh]);
int i=-1;
for(i = ilow; i <= ihigh; i++) {
if(root.val == inorder[i]) {
break;
}
}
if(i != ilow) root.left = buildTree(inorder, postorder, ilow, i-1, plow,plow+i-ilow-1);
if(i != ihigh) root.right = buildTree(inorder,postorder, i+1, ihigh, plow+i-ilow, phigh-1);
return root;
}
相关文章推荐
- leetcode 179 Largest Number
- leetcode 24 Swap Nodes in Pairs
- leetcode 2 Add Two Numbers 方法1
- leetcode 2 Add Two Numbers 方法2
- [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
- 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 题解
- LeetCode [Day 5] Longest Palindromic Substring 题解
- LeetCode [Day 6] ZigZag Conversion 题解