[LintCode] 前序遍历和中序遍历树构造二叉树 Construct Binary Tree from Preorder and Inorder Traversal
2016-04-17 22:27
501 查看
根据前序遍历和中序遍历树构造二叉树.
注意事项
你可以假设树中不存在相同数值的节点.
样例
给出中序遍历:[1,2,3]和前序遍历:[2,1,3]. 返回如下的树:
2
/ \
1 3
Given preorder and inorder traversal of a tree, construct the binary tree.
Notice
You may assume that duplicates do not exist in the tree.
Example
Given in-order [1,2,3] and pre-order [2,1,3], return a tree:
2
/ \
1 3
注意事项
你可以假设树中不存在相同数值的节点.
样例
给出中序遍历:[1,2,3]和前序遍历:[2,1,3]. 返回如下的树:
2
/ \
1 3
Given preorder and inorder traversal of a tree, construct the binary tree.
Notice
You may assume that duplicates do not exist in the tree.
Example
Given in-order [1,2,3] and pre-order [2,1,3], return a tree:
2
/ \
1 3
/** * Definition of TreeNode: * public class TreeNode { * public int val; * public TreeNode left, right; * public TreeNode(int val) { * this.val = val; * this.left = this.right = null; * } * } */ public class Solution { /** *@param preorder : A list of integers that preorder traversal of a tree *@param inorder : A list of integers that inorder traversal of a tree *@return : Root of a tree */ public TreeNode buildTree(int[] preorder, int[] inorder) { if(null == preorder || null == inorder || preorder.length != inorder.length || preorder.length == 0) return null; return createTree(preorder, 0, preorder.length-1, inorder, 0, inorder.length-1); } public TreeNode createTree(int[] preorder, int lp, int rp, int[] inorder, int li, int ri) { if(lp > rp || li > ri) return null; TreeNode root = new TreeNode(preorder[lp]); int inlo = location(inorder, preorder[lp]); root.left = createTree(preorder, lp+1, lp+inlo-li,inorder, li, inlo-1); root.right = createTree(preorder, lp+inlo-li+1, rp,inorder, inlo+1, ri); return root; } public int location(int[] nums, int key) { int i = 0; while(nums[i++] != key); return --i; } }
相关文章推荐
- 技术常用网址
- AngularJS最理想开发工具WebStorm
- 第7周项目2-友元类
- findLadders--BFS--a到z 每个字母尝试着换。
- 原型模式
- 每天一篇python:简单爬虫下载图片篇
- SVM核技巧的经典解释
- HDU 5666
- iOS --- 理解Runtime机制及其使用场景
- Leetcode题解15 58. Length of Last Word
- 在texlive下使用CJK的3条小心得
- Java设置GUI的窗口图标
- PHP文件下载功能
- BFS模板
- Light oj 1149 - Factors and Multiples【最大匹配】
- 使用Windows上SourceInsight工具建立分析Linux下uboot源码工程
- 彩色视频转换为灰度视频输出
- LeetCode 101. Symmetric Tree
- java学习笔记(2)基本数据类型对象包装类
- CSS相关知识二