创建二叉树
来源:互联网 发布:linux tail 指定行 编辑:程序博客网 时间:2024/06/01 20:56
给定一棵二叉树的先序遍历和中序遍历,得到该二叉树。
代码:
public class BuildTree {
public static void main(String[] args) {
int[] preorder = {7,10,4,3,1,2,8,11};
int[] inorder = {4,10,3,1,7,11,8,2};
TreeNode root = buildByPreAndIn(preorder, 0, preorder.length-1, inorder, 0, inorder.length-1);
preOrder(root);
System.out.println();
inOrder(root);
}
public static TreeNode buildByPreAndIn(int[] preorder, int begin1, int end1, int[] inorder, int begin2, int end2){
if(begin1 > end1 || begin2 > end2){
return null;
}
int rootdata = preorder[begin1];
TreeNode root = new TreeNode(rootdata);
int rootdataindex = findIndexByOrder(inorder, rootdata, begin2, end2);
int sub = rootdataindex - begin2;
TreeNode left = buildByPreAndIn(preorder, begin1+1, begin1+sub, inorder, begin2, rootdataindex-1);
TreeNode right = buildByPreAndIn(preorder, begin1+sub+1, end1, inorder, rootdataindex+1, end2);
root.left = left;
root.right = right;
return root;
}
public static void preOrder(TreeNode root){
if(root != null){
System.out.print(root.val + " ");
preOrder(root.left);
preOrder(root.right);
}
}
public static void inOrder(TreeNode root){
if(root != null){
inOrder(root.left);
System.out.print(root.val + " ");
inOrder(root.right);
}
}
public static int findIndexByOrder(int[] order, int rootdata, int begin2, int end2){
for(int i=begin2; i<=end2; ++i){
if(order[i] == rootdata){
return i;
}
}
return -1;
}
}
class TreeNode{
int val;
TreeNode left;
TreeNode right;
public TreeNode(int val){
this.val = val;
}
}
- 创建二叉树 创建单链表
- 树----创建二叉树
- 创建二叉树
- 二叉树的创建
- 创建二叉树
- 创建二叉树
- 二叉树的创建
- 前序中序创建二叉树
- 创建二叉树
- java 二叉树创建
- java创建二叉树
- 创建二叉树
- 二叉树创建
- 二叉树的创建。
- 创建二叉树
- 创建二叉树
- java创建二叉树
- 创建二叉树
- jquery 中 closest和parent用法
- eclipse到android studio遇到的问题
- iOS 中几种不同通信模式的优缺点
- d3选择集合核心方法(二):data与datum
- Error:(34) Error: "xxx" is translated here but not found in default locale [ExtraTrans
- 创建二叉树
- 为Android系统或你的应用提供搜索功能--开始使用搜索功能
- Hadoop YARN RPC实现
- 挂机型外挂开发-框架设计
- Hibernate4学习笔记(二): 向数据表中添加数据
- AP AR 查看那些单据(invoice, payment, transaciton, receipt等)还没有创建会计分录或分录出错
- 【译】我从编程总结的 22 个经验
- code collect
- Quartz教程二:API,Job和Trigger