Given preorder and inorder traversal of a tree, construct the binary tree.
Note:
You may assume that duplicates do not exist in the tree.
找到规律,递归的解决左子树和右子树。
/** * Definition for binary tree * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class Solution { //java public TreeNode buildSubTree(int [] preorder, int pbegin, int pend, int [] inorder, int ibegin, int iend){ TreeNode root = null; if(pbegin > pend || ibegin > iend) return root; if(pbegin == pend){ TreeNode tmp = new TreeNode(preorder[pbegin]); root = tmp; return root; } int value = preorder[pbegin]; int pos = 0; for(int i = ibegin; i <=iend; i++){ if(value == inorder[i]){ pos = i; break; } } int lnum = pos - ibegin; int rnum = iend - pos; TreeNode ltreeNode = buildSubTree(preorder,pbegin+1,pbegin+lnum,inorder,ibegin,pos-1); TreeNode rTreeNode = buildSubTree(preorder, pbegin+lnum+1, pend, inorder, pos+1, iend); TreeNode tmp = new TreeNode(preorder[pbegin]); tmp.left = ltreeNode; tmp.right = rTreeNode; root = tmp; return root; } public TreeNode buildTree(int[] preorder, int[] inorder) { TreeNode root = null; if(preorder.length == 0) return root; root = buildSubTree(preorder , 0 , preorder.length-1, inorder, 0, inorder.length-1); return root; } }
[leetcode]Construct Binary Tree from Preorder and Inorder Traversal
原文地址:http://blog.csdn.net/chenlei0630/article/details/41408319