从中序与后序遍历序列构造二叉树-106

打印 上一主题 下一主题

主题 884|帖子 884|积分 2652

标题描述

给定两个整数数组 inorder 和 postorder ,其中 inorder 是二叉树的中序遍历, postorder 是同一棵树的后序遍历,请你构造并返回这颗 二叉树 。
解题思路

这题我们的思路还是递归去构造我们的二叉树,首先标题给出二叉树的中序遍历和后序遍历,由后序遍历我们可以确定我们当前这颗二叉树的根节点,然后转到中序遍历我们可以根据根节点判断哪些节点是左孩子,哪些节点是右孩子,然后再去后序遍历中判断左孩子节点的后序遍历次序和右孩子节点的后序遍历次序,然后我们递归一层一层往下去构建我们的二叉树就行了
代码实例

[code]import java.util.*;class Solution {    public TreeNode buildTree(int[] inorder, int[] postorder) {        if(postorder.length==0){            return null;        }        int rootValue=postorder[postorder.length-1];        TreeNode root=new TreeNode(rootValue);        if(postorder.length==1){            return root;        }               int rootIndex;        for(rootIndex=0;rootIndex
回复

使用道具 举报

0 个回复

倒序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

羊蹓狼

金牌会员
这个人很懒什么都没写!
快速回复 返回顶部 返回列表