构建二叉树

以#为终止符构建先序二叉树

eg. 12#4#5##3##

public int index = 0;
public TreeNode constructPreorderTree(char[] str){
    if(str[index++] == '#') return null;
    TreeNode node = new TreeNode(str[index]-'0');
    index++;
    node.left = constructPreorderTree(str);
    node.right = constructPreorderTree(str);
    return node;
}

以#为终止符构建中序二叉树

eg. #2#4#5#1#3#

public int index = 0;
public TreeNode constructInorderTree(char[] str){
    if(str[index++] == '#') return null;
    TreeNode left = constructInorderTree(str);
    TreeNode node = new TreeNode(str[index]-'0');
    node.left = left;
    index++;
    node.right = constructInorderTree(str);
    return node;
}

以#为终止符构建后序二叉树

eg. ####542##31

public int index = 0;
public TreeNode constructPostorderTree(char[] str){
    if(str[index++] == '#') return null;
    TreeNode left = constructPostorderTree(str);
    TreeNode right = constructPostorderTree(str);
    TreeNode node = new TreeNode(str[index]-'0');
    node.left = left;
    node.right = right;
    index++;
    return node;
}

给先序中序重构二叉树

12453
24513
思路:每次遍历先序找到根,根据找到的根和中序遍历序列可以将树分成两半了。不断递归。

int preIter = 0;
public TreeNode constructFromPreAndIn(int[] pre, int[] in){
    return construct(pre, in, 0, in.length-1);
}

public TreeNode construct(int[] pre, int[] in, int start, int end){
    if(start > end) return null;
    int val = pre[preIter++];
    TreeNode root = new TreeNode(val);
    int i = start;
    for(; i <= end && in[i] != val; i++);
    root.left = construct(pre, in, start, i-1);
    root.right = construct(pre, in, i+1, end);
    return root;
}

给后序中序重构二叉树

int postIter;
public TreeNode constructFromPreAndIn(int[] in, int[] post){
    postIter = post.length-1;
    return construct(post, in, 0, in.length-1);
}

public TreeNode construct(int[] post, int[] in, int start, int end){
    if(start > end) return null;
    int val = post[postIter--];
    TreeNode root = new TreeNode(val);
    int i = start;
    for(; i <= end && in[i] != val; i++);
    root.right = construct(post, in, i+1, end);
    root.left = construct(post, in, start, i-1);
    return root;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值