106. Construct Binary Tree from Inorder and Postorder Traversal

Given inorder and postorder traversal of a tree, construct the binary tree.

Note:

You may assume that duplicates do not exist in the tree.

For example, given

inorder = [9,3,15,20,7]
postorder = [9,15,7,20,3]

Return the following binary tree:

    3
   / \
  9  20
    /  \
   15   7

 

 

 

题目解析:给一个中序遍历数组和一个后序遍历的数组,推导出它对应的二叉搜索树。

根据后序遍历的特点,后序遍历数组的最后一位是根节点的值,然后根据根节点的值去中序遍历数组中查找相应的值,在中序遍历数组中,根节点前边的是左子树的中序遍历情况,可以算出左子树的节点个数为s,相对应的在后序遍历数组中前s项就是左子树的后序遍历情况。然后根据使用递归,就可以还原出二叉搜索树。

例如:

中序遍历:9, 3, 15, 20, 7

后序遍历:9, 15, 7, 20, 3

3是整个BST的根节点,在中序遍历中,3之前的节点是左子树的节点,也就是只有一个9,相对应的在后序遍历中9就是左子树的后序遍历。

 

 

public class ConstructBSTFromInorderAndPostorderTraversal {

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

                List<Integer> postList = new ArrayList<>();

                List<Integer> midList = new ArrayList<>();

                for (int i : postorder) {

                        postList.add(i);

                }

                for (int i : inorder) {

                        midList.add(i);

                }

                return buildTree(midList, postList);

        }



        private TreeNode buildTree(List<Integer> midList, List<Integer> postList) {

                if(postList.isEmpty() || midList.isEmpty())

                        return null;

                int value = postList.get(postList.size() - 1);



                TreeNode root = new TreeNode(value);

                int len = midList.indexOf(value);

                root.left = buildTree(midList.subList(0, len), postList.subList(0, len));

                root.right = buildTree(midList.subList(len+1, midList.size()), postList.subList(len, midList.size()-1));

                return root;

        }

}

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值