您的位置:首页 > 其它

树的算法 已知二叉树的前序序列和中序序列求解树

2015-10-23 16:02 267 查看
题目: 已知二叉树的前序序列和中序序列求解树

比如

    6

  4    8

3  5   7

前序序列为6,4,3,5,8,7

中序序列为3,4,5,6,7,8

思路: 前序遍历序列的第一个元素必为根节点 则中序遍历序列中,该节点之前的为左子树,该节点之后的为右子树,若该节点之前没有节点,则左子树为空,反之右子树为空,

截取个子树的前序和中序序列,重复上述逻辑递归求解

我自己的思路是只根据前序遍历序列也可得到:同理前序第一个元素为根节点,向后依次比较后续元素,直到找到第一个比根元素大的,则该元素与根元素之间的所有元素(不包括)为左子树,该元素之后的所有元素(包括)为右子树,对子树使用相同逻辑递归即可,但需要判断子树为空的情况

package com.rui.microsoft;

import java.util.Arrays;

public class Tree_BuildTreeByPreMid {

public static void main(String[] args) {

int[] pre = {6,4,3,5,8,7};
//int[] mid = {3,4,5,6,7,8};

Node root = Tree_BuildTreeByPreMid.build(pre);
System.out.println(root.value);
}

public static Node build(int[] pre){
int rootV = pre[0];
Node root = new Node(rootV);

int left = 1;
while(left < pre.length && pre[left] < rootV) left++;

//No left tree, because the pointer left has not changed
if(left == 1){
root.left = null;
}else{
int[] leftArray = Arrays.copyOfRange(pre, 1, left);
root.left = build(leftArray);
}

//No right tree, because the pointer left has been moved to the end of the array
if(left == pre.length){
root.right = null;
}else{
int[] rightArray = Arrays.copyOfRange(pre, left, pre.length);
root.right = build(rightArray);
}

return root;
}

static class Node {
int value;
Node left;
Node right;
public Node(int v){
this.value = v;
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: