leetcode--Construct Binary Tree from Inorder and Postorder Traversal

来源:互联网 发布:网络博客评级网站 编辑:程序博客网 时间:2024/06/06 01:49

Given inorder and postorder traversal of a tree, construct the binary tree.

Note:
You may assume that duplicates do not exist in the tree.


题意:已经二叉树的中序遍历和后续遍历,重构二叉树

分类:二叉树


解法1:一般重构二叉树的问题,我们都使用递归,然后传入的参数是start,end来标记数组的一段。

这个问题也不例外。

先从后序中找到最后一个节点,就是根节点

然后在中序找到根节点,根节点将中序分成两部分,其实就是左右子树的中序遍历

再再后序从后向前找相同的数目,这个节点把后序分成两部分,其实就是左右子树的后序遍历

递归重复上述过程

递归出口是数组只有一个元素,也就是start==end

/** * Definition for a binary tree node. * public class TreeNode { *     int val; *     TreeNode left; *     TreeNode right; *     TreeNode(int x) { val = x; } * } */public class Solution {    public TreeNode buildTree(int[] inorder, int[] postorder) {return hepler(postorder, 0, postorder.length-1, inorder, 0, inorder.length-1);    }public TreeNode hepler(int[] postorder,int pstart,int pend,int[] inorder,int istart,int iend){    if(pstart>pend) return null;if(pstart==pend) return new TreeNode(postorder[pstart]);int f = postorder[pend];TreeNode t = new TreeNode(f);int mid = istart;for(;mid<=iend;mid++){if(f==inorder[mid]) break;}int len = mid-istart;t.left = hepler(postorder, pstart, pstart+len-1, inorder, istart, mid-1);t.right = hepler(postorder, pstart+len, pend-1, inorder, mid+1, iend);return t;}}

0 0
原创粉丝点击