您的位置:首页 > 其它

LeetCode Construct Binary Tree from Inorder and Postorder Traversal

2015-11-26 11:18 531 查看
题目:

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

题意:

给定一棵树的中序遍历和后序遍历序列,求这棵二叉树的结构。

题解:

首先我们可以确定中序遍历和后序遍历是可以唯一确定一棵二叉树的,然后此题和之前的通过先序和中序遍历序列确定二叉树类似,都是通过递归来做,那么具体还是有一些区别。现在后序遍历的最后的那个节点是二叉树的根节点,然后就要在中序遍历序列中找到这个节点,然后就是不停地递归求左子树和右子树。但是其中在递归的时候的那些参数要特别当心,尤其是长度和下标,不要搞混了。

public class Solution
{
public TreeNode buildTree(int[] inorder, int[] postorder)
{
if(inorder == null || postorder == null || inorder.length == 0 || postorder.length == 0 || inorder.length != postorder.length)
return null;
return Construct(inorder,0,postorder,postorder.length - 1,postorder.length);
}
public TreeNode Construct(int[] inorder,int start,int[] postorder,int end,int length)
{
if(length <= 0)
return null;
int value = postorder[end];
TreeNode root = new TreeNode(value);
if(length == 1)
return root;
int i = start;
while(i < postorder.length)
{
if(inorder[i] == value)
break;
i++;
}
System.out.println(i);
//System.out.println(end);
root.left = Construct(inorder,start,postorder,end - length + i - start,i - start); //这里的第4项是后序遍历的结束点
root.right = Construct(inorder,i + 1,postorder,end-1,length - i + start - 1); //第5项是每一段分割的长度
return root;
}
}这里的第4项和第5项参数一定要当心,分别表示的是后序遍历序列中的要分割的那一段的尾节点的下标和长度,所以要当心关于这两个参数的意义,以免在写递归函数的时候出现错误。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: