从中序与后序遍历序列构造二叉树-106
标题描述给定两个整数数组 inorder 和 postorder ,其中 inorder 是二叉树的中序遍历, postorder 是同一棵树的后序遍历,请你构造并返回这颗 二叉树 。
解题思路
这题我们的思路还是递归去构造我们的二叉树,首先标题给出二叉树的中序遍历和后序遍历,由后序遍历我们可以确定我们当前这颗二叉树的根节点,然后转到中序遍历我们可以根据根节点判断哪些节点是左孩子,哪些节点是右孩子,然后再去后序遍历中判断左孩子节点的后序遍历次序和右孩子节点的后序遍历次序,然后我们递归一层一层往下去构建我们的二叉树就行了
代码实例
import java.util.*;class Solution { public TreeNode buildTree(int[] inorder, int[] postorder) { if(postorder.length==0){ return null; } int rootValue=postorder; TreeNode root=new TreeNode(rootValue); if(postorder.length==1){ return root; } int rootIndex; for(rootIndex=0;rootIndex
页:
[1]