前序与中序遍历序列构造二叉树 中序与后序遍历序列构造二叉树
105. 从前序与中序遍历序列构造二叉树
根据前序遍历和中序遍历,我们可以发现前序遍历的第一个元素就为根元素,在中序遍历中找到这个元素,那么中序遍历中左边为根元素的左子树,右边为右子树,依次递归。
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ class Solution { public TreeNode buildTree(int[] preorder, int[] inorder) { int len1 = preorder.length-1; int len2 = inorder.length-1; TreeNode root = bulidTree(preorder,0,len1,inorder,0,len2); return root; } public TreeNode bulidTree(int[] preorder, int start1,int end1,int[] inorder,int start2, int end2){ if(start1>end1 || start2>end2){ return null; } TreeNode node = new TreeNode(preorder[start1]); for(int k = start2; k<=end2; k++){ if(preorder[start1] == inorder[k]){ node.left = bulidTree(preorder,start1+1,start1+k-start2,inorder,start2,k-1); node.right = bulidTree(preorder,start1+k-start2+1,end1,inorder,k+1,end2); } } return node; } }
106. 从中序与后序遍历序列构造二叉树
类似上一题的思路。后序遍历的最后一个节点即为根节点,在中序遍历中找到,然后中序遍历左边为根节点左子树,右边为根节点右子树。
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ class Solution { public TreeNode buildTree(int[] inorder, int[] postorder) { int len1 = inorder.length-1; int len2 = postorder.length-1; return bulid(inorder,0,len1,postorder,0,len2); } public TreeNode bulid(int[] p1,int start1, int end1,int[] p2,int start2, int end2){ if(start1>end1||start2>end2) return null; int mid=0; for(int i=start1;i<=end1;i++){ if(p1[i]==p2[end2]){ mid = i; break; } } TreeNode node = new TreeNode(p2[end2]); node.left = bulid(p1,start1,mid-1,p2,start2,mid-start1+start2-1); node.right = bulid(p1,mid+1,end1,p2,end2-end1+mid,end2-1); return node; } }