Construct Binary Tree from Inorder and Postorder Traversal(给出中序后序求二叉树)
来源:互联网 发布:网络ip地址怎么修改 编辑:程序博客网 时间:2024/06/06 00:34
题目原型:
Given inorder and postorder traversal of a tree, construct the binary tree.
Note:
You may assume that duplicates do not exist in the tree.
基本思路:
根据后序序列找到根,然后根据根节点分割中序序列。
public TreeNode buildTree(int[] inorder, int[] postorder){if(inorder.length==0&&postorder.length==0)return null;else{//找到根节点的值TreeNode root = new TreeNode(postorder[postorder.length-1]);//在中序序列中找到根节点int targetIndex = -1;for(int i = 0;i<inorder.length;i++){if(inorder[i]==postorder[postorder.length-1]){targetIndex = i;break;}}//求出左子树和右子树的长度int lenOfLeft = targetIndex;int lenOfRight = inorder.length-targetIndex-1;//求出左子树int[] leftInorder = new int[lenOfLeft];int[] leftPostorder = new int[lenOfLeft];for(int i = 0;i<targetIndex;i++){leftInorder[i] = inorder[i];leftPostorder[i] = postorder[i];}root.left = buildTree(leftInorder, leftPostorder);//求出右子树int[] rightInorder = new int[lenOfRight];int[] rightPostorder = new int[lenOfRight];for(int i = targetIndex+1;i<inorder.length;i++){rightInorder[i-targetIndex-1] = inorder[i];rightPostorder[i-targetIndex-1] = postorder[i-1];}root.right = buildTree(rightInorder, rightPostorder);return root;}}}
0 0
- Construct Binary Tree from Inorder and Postorder Traversal(给出中序后序求二叉树)
- Construct Binary Tree from Preorder and Inorder Traversal (给出前序中序求二叉树)
- Construct Binary Tree from Inorder and Postorder Traversal(medium)
- Construct Binary Tree from Inorder and Postorder Traversal 中序和后序遍历二叉树
- Construct Binary Tree from Inorder and Postorder Traversal 中序和后序重建二叉树
- Leetcode Construct Binary Tree from Inorder and Postorder Traversal 中序后序遍历重组二叉树
- 105\106. Construct Binary Tree from Inorder and Postorder\Preorder Traversal&重建二叉树
- leetcode:二叉树之Construct Binary Tree from Inorder and Postorder Traversal
- 重建二叉树106. Construct Binary Tree from Inorder and Postorder Traversal
- 5.2.2—二叉树的构建—Construct Binary Tree from Inorder and Postorder Traversal
- 【二叉树经典问题】106. Construct Binary Tree from Inorder and Postorder Traversal
- Construct Binary Tree from Inorder and Postorder Traversal 根据中序和后序序列生成二叉树(重重)
- 【LeetCode-面试算法经典-Java实现】【106-Construct Binary Tree from Inorder and Postorder Traversal(构造二叉树II)】
- *(leetcode) Construct Binary Tree from Inorder and Postorder Traversal (tree)
- LeetCode[Tree]: Construct Binary Tree from Inorder and Postorder Traversal
- LeetCode: Construct Binary Tree from Inorder and Postorder Traversal
- [LeetCode]Construct Binary Tree from Inorder and Postorder Traversal
- LeetCode Construct Binary Tree from Inorder and Postorder Traversal
- 0308来杭州参加招聘会,应聘C++岗位,面试官问的问题和笔试做的笔试题做下记录,以免遗忘.
- Cordys云开通服务开发者指南(二)
- 第一周:欧几里得求两个数的公约数
- MOD 之"Hello World"
- 关于在Ubuntu上面安装使用QQ
- Construct Binary Tree from Inorder and Postorder Traversal(给出中序后序求二叉树)
- Java中的i++和i--
- zoj1091题解
- 作业3
- Learning the parts of object by NMF
- HDU 1576 A/B
- <<OCM实验选讲>> 第五课 数据备份恢复实验
- Struts2标签
- cocos2dx场景切换小例子