内容简介:根据一棵树的中序遍历与后序遍历构造二叉树。注意:你可以假设树中没有重复的元素。
题目
根据一棵树的中序遍历与后序遍历构造二叉树。
注意:
你可以假设树中没有重复的元素。
例如,给出
中序遍历 inorder = [9,3,15,20,7]
后序遍历 postorder = [9,15,7,20,3]
返回如下的二叉树:
3 / \ 9 20 / \ 15 7
题解
根据前序和中序可以构造一颗二叉树,根据中序和后续也可以构建一颗二叉树。
反正必须要有中序才能构建,因为没有中序,你没办法确定树的形状。
比如先序和后序是不能构建唯一的一颗二叉树的。
例如:
先序为:[1, 2]
后序为:[2, 1]
可以构建如下
1 / 2
1 \ 2
这个面试官也会问的。
回到这个题目。
那回到这个题目, 其实思路比较好想到,就是如何划分子问题,然后递归的构建左子树和右子树。
inorder = [9,3,15,20,7]
postorder = [9,15,7,20,3]
因为后序后遍历根节点,后续最后一个节点为整棵树的根节点,可以确定根节点为3;
再根据中序得到:
leftInOrder = [9]
RightInOrder = [15, 20 ,7]
又由于中序和先序的数组大小应该相同的,
所以,
LeftPostOrder = [9]
RightPostOrder = [15, 7, 20]
至此,划分为子问题:
leftInOrder = [9]
LeftPostOrder = [9]
构建左子树。
RightPreOrder = [20, 15, 7]
RightPostOrder = [15, 7, 20]
构建右子树。
class Solution { public TreeNode buildTree(int[] inorder, int[] postorder) { return helper(inorder, postorder, postorder.length - 1, 0, inorder.length - 1); } public TreeNode helper(int[] inorder, int[] postorder, int postEnd, int inStart, int inEnd) { if (inStart > inEnd) { return null; } int currentVal = postorder[postEnd]; TreeNode current = new TreeNode(currentVal); int inIndex = 0; for (int i = inStart; i <= inEnd; i++) { if (inorder[i] == currentVal) { inIndex = i; } } TreeNode left = helper(inorder, postorder, postEnd - (inEnd- inIndex) - 1, inStart, inIndex - 1); TreeNode right = helper(inorder, postorder, postEnd - 1, inIndex + 1, inEnd); current.left = left; current.right = right; return current; } }
热门阅读
- 技术文章汇总
- 【Leetcode】103. 二叉树的锯齿形层次遍历
- 【Leetcode】102. 二叉树的层次遍历
- 【Leetcode】101. 对称二叉树
- 【Leetcode】100. 相同的树
- 【Leetcode】98. 验证二叉搜索树
手撕代码QQ群:805423079, 群密码:1024
以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网
猜你喜欢:- 力扣(105):从前序与中序遍历序列构造二叉树
- LeetCode105. 从前序与中序遍历序列构造二叉树
- 【Leetcode】105. 从前序与中序遍历序列构造二叉树
- 数组常见的遍历循环方法、数组的循环遍历的效率对比
- C++拾趣——STL容器的插入、删除、遍历和查找操作性能对比(Windows VirtualStudio)——遍历和删除
- Js遍历数组总结
本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。
Chinese Authoritarianism in the Information Age
Routledge / 2018-2-13 / GBP 115.00
This book examines information and public opinion control by the authoritarian state in response to popular access to information and upgraded political communication channels among the citizens in co......一起来看看 《Chinese Authoritarianism in the Information Age》 这本书的介绍吧!