通过中序和后序遍历构造二叉树

原题

  Given inorder and postorder traversal of a tree, construct the binary tree.
  Note:
  You may assume that duplicates do not exist in the tree.

题目大意

  给定一个中序遍历和后序遍历序列,构造一棵二叉树
  注意:
  树中没有重复元素

解题思路

  后序遍历的最后一个元素就是树的根结点(值为r),在中序遍历的序列中找值为r的位置idx,idx将中序遍历序列分为左右两个子树,对应可以将后序遍历的序列分在两个子树,递归对其进行求解。

代码实现

 

public class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;
    TreeNode(int x) { val = x; }
}

 

算法实现类

public class Solution {

    public TreeNode buildTree(int[] inorder, int[] postorder) {

        // 参数检验
        if (inorder == null || postorder == null || inorder.length == 0
                || inorder.length != postorder.length) {
            return null;
        }

        // 构建二叉树
        return solve(inorder, 0, inorder.length - 1, postorder, 0, postorder.length - 1);
    }

    /**
     * 构建二叉树
     *
     * @param inorder   中序遍历的结果
     * @param x         中序遍历的开始位置
     * @param y         中序遍历的结束位置
     * @param postorder 后序遍历的结果
     * @param i         后序遍历的开始位置
     * @param j         后序遍历的结束位置
     * @return 二叉树
     */
    public TreeNode solve(int[] inorder, int x, int y, int[] postorder, int i, int j) {

        if (x >= 0 && x <= y && i >= 0 && i <= j) {
            // 只有一个元素,(此时也有i=j成)
            if (x == y) {
                return new TreeNode(postorder[j]);
            }
            // 多于一个元素,此时也有i<j
            else if (x < y) {
                // 创建根结点
                TreeNode root = new TreeNode(postorder[j]);

                // 找根结点在中序遍历的下标
                int idx = x;
                while (idx < y && inorder[idx] != postorder[j]) {
                    idx++;
                }

                // 左子树非空,构建左子树
                int leftLength = idx - x;
                if (leftLength > 0) {
                    // i, i + leftLength - 1,前序遍历的左子树的起始,结束位置
                    root.left = solve(inorder, x, idx - 1, postorder, i, i + leftLength - 1);
                }

                // 右子树非空,构建右子树
                int rightLength = y - idx;
                if (rightLength > 0) {
                    // i + leftLength, j - 1,前序遍历的右子树的起始,结束位置
                    root.right = solve(inorder, idx + 1, y, postorder, i + leftLength, j - 1);
                }

                return root;
            } else {
                return null;
            }
        }

        return null;
    }
}

转载于:https://my.oschina.net/u/2822116/blog/809463

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值