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.
思路:树形结构的中序和后序,找好相对位置,并控制好边界
java代码:
- TreeNode helper(int[] inorder,int ist,int[] postorder,int pst,int len) {
- if(len<1) return null; //无左节点或者右节点
- if(len==1) {
- return new TreeNode(inorder[ist]);
- }
- int k = pst + len - 1;
- int tmp = postorder[k];
- int i=0;
- for(i=0;i<len;i++) {
- if(inorder[ist+i] == tmp) break;
- }
- TreeNode root = new TreeNode(inorder[ist+i]);
- root.left = helper(inorder,ist,postorder,pst,i);
- root.right = helper(inorder,ist+i+1,postorder,pst+i,len-1-i); //len - 1 - i,已经处理一个节点了
- return root;
- }
- public TreeNode buildTree(int[] inorder, int[] postorder) {
- int ilen = inorder.length;
- int plen = postorder.length;
- if(ilen == 0) return null;
- if(ilen != plen) return null;
- return helper(inorder,0,postorder,0,ilen);
- }

浙公网安备 33010602011771号